Tuples in Swift
Korey Hinton -> Blog -> iOS -> Tuples in Swift
Swift Tuples
Swift tuples store 2 values and each value can be of any type and the type can be inferred. Swift tuples can be useful for storing data temporarily in the current scope to quickly group values together and then get to those values quickly. It is recommended, however, to use a struct or class instead if you need additional complexity or if you are going to extensively use the data throughout your app.
Basic Usage
You can access an unnamed tuple either by assigning both values to a variable, or assigning just 1 of the 2 values and use the wildcard _ for the value you don't need, or by accessing the 0 or 1 property. ie: myTuple.0
. Below you can see how to assign an unnamed tuple and also the 3 ways to access its values.
let post = ("My Post","My Description") let (title, description) = post println("My latest blog post is titled \(title) and can be described as \(description).") //>> My latest blog post is titled My Post and can be described as My Description. let song = ("Eye of the Tiger","Survivor") var (currentSong, _) = song println("All I needed was the current song: \(currentSong)") //>> All I needed was the current song: Eye of the Tiger let location = ("Salt Lake City", "UT") println("This was written in \(location.0), \(location.1).") //>> This was written in Salt Lake City, UT.
Named Tuples
Named tuples are being added to a lot of programming languages. I know I've seen them in Python. It is a very convenient way to quickly store 2 values together and then later access the values by name. This data structure can be very useful but shouldn't replace major model data objects in your app.
let namedTuple = (itemID: 5559, itemDescription:"Milk") println("Got \(namedTuple.itemDescription)?") //>> Got Milk? func getStartingPosition() -> (x: Int, y: Int) { return (0,0) } var origin = getStartingPosition() println("Starting at position (\(origin.x),\(origin.y))") //>> Starting at position (0,0)
Iterating dictionaries with tuples
You'll probably find many uses for swift tuples. Apple did. Look below, you can iterate the key-value pairs of a dictionary as tuples.
var students = [1: "Bob",2: "Mary"] for (studentID, studentName) in students { println("\(studentID): \(studentName)") } //>> 1: Bob //>> 2: Mary
Switch statement on a tuple
Switching on a tuple is straight forward. You can use _ as a wildcard value if all you care about is the other value.
let point = (0,0) switch point { case(0,_): println("y-axis") case(_,0): println("x-axis") default: println("not on x-axis, not on y-axis") } //>> x-axis //>> y-axis
When to use tuples
- Return multiple values from a function
Tuples can be used to return multiple values from a function.
- Group data together
Tuples can group small pieces of related data without having to break out an entire class
- Easy access
Tuples make it easy and quick to create, access, and modify a data set.