I was looking for a bit of information on Tuples in Swift for an app I was working on, and decided it would be best to gather what I learn into one, easy to access place.
Tuples are a compound type in Swift, which basically means that they can hold multiple values. A compound type can either contain what are called “named types”, which include classes, structures, and enumerations (also protocols, but since they don’t store values directly, I felt I should mention them separately), as well as other compound types. That means a tuple can hold other tuples. Another compound type a tuple can contain is the “function type,” which is a different way of referring to the type that describes closures (specifically the “() ->() ” style of type, which functions and methods also conform to. That also goes the other way, that a function type can hold other compound types, like the Tuple, and other closures, which we’ve seen in my previous post Closures and Capturing Values in Swift.
While technically inaccurate, you can conceptually think of Tuples kind of like a class or structure that you can make on the fly, without having to define a full fledged class or structure (nested or otherwise). According to Apple’s iBook though, they should probably only be used for temporary values, like to return them from a function. It doesn’t go into detail why, but if I had to guess, they were probably optimized for quick creation, at the cost of how it stores them. Nonetheless, one of the great new capabilities of Swift is multiple return types, and tuples are what Swift uses to achieve this, since they are technically returning a single value (the tuple itself).
One thing people are sometimes curious about tuples is how it is pronounced. Well, according to Dictionary.com, there are two valid pronunciations. In dictionary pronunciation code: /ˈtjʊpəl and ˈtʌpəl/. For anybody curious, ʊ is the sound of the “oo” in “took”, ə (a schwa) is how the a sounds in “about”, and ʌ (a wedge) is the sound of the “u” in “gut.” That means that those are pronounced (roughly) as too-puhl and tuh-puhl, respectively. I was digging around for examples of where they were from, only to find out both pronunciations happen for those examples as well, but they are basically from the end of words like “quadruple,” “quintuple,” and “octuple” (notice the “tuple” at the end of each). I personally prefer too-puhl, myself.
With readers coming from the US, the UK, and many other places, I suppose the pronunciation will vary. For those that listen to the Accidental Tech Podcast, apparently Dictionary.com agrees with both sides: huhv-er (/ˈhʌv ər) and hov-er (ˈhɒv-/ ər). For those of you that don’t, you really should go check it out.
Anyway though, you didn’t come here to learn about English phonetics, it’s time to learn how to use tuples in Swift!
Creating a Tuple
There are a few ways to create tuples. Technically, I believe this one is called the “Tuple Pattern”. It pretty much looks exactly like an array literal, except with parenthesis (instead of square brackets), and it can take any type (as opposed to the same type in an Array):
let firstHighScore = ("Mary", 9001)
The above is the easiest way. There is another way to make a tuple that takes advantage of Swift’s named parameters. You will see why this can be helpful a bit later:
let secondHighScore = (name: "James", score: 4096)
That really is all there is to it. If this was a struct, you would have to write out the structure somewhere in your code, with its internal properties and the like. If it were a class, you would even have to write an initializer for it yourself. With tuples, all you have to do is put the values you want into a pair of parenthesis, with each value separated by commas. If you really want, you can even name them for later use.
Reading from a Tuple
There are several ways to read from a tuple. Which one you use will depend on the situation where this tuple is being used. You can use any of them at any time, but there will probably be situations where one will be easier to use than the others.
First, you can bind the tuple’s contents using some pattern matching:
let (firstName, firstScore) = firstHighScore
In the case of this one, since we are using pattern matching, you can also use the underscore to ignore a value if you only want some of them. If we only wanted to read the score from our tuple, you could do the following:
let (_, onlyFirstScore) = firstHighScore
They are also given very imaginative default names that count up from 0, so you could also write:
let theName = firstHighScore.0 let theScore = firstHighScore.1
Finally, if you named them when defining the tuple, you can access them that way with more dot-syntax:
let secondName = secondHighScore.name let secondScore = secondHighScore.score
Returning a Tuple from a Function
This was covered in my previous post Functions in Swift: Parameters and Return Types, but since this is all about Swift tuples, I’ll include it here to have it all rounded up in one place.
Here’s a function that returns our high score:
func getAHighScore() -> (name: String, score: Int) { let theName = "Patricia" let theScore = 3894 return (theName, theScore) }
So there we named what they would be in the function’s return type, and when we actually created the tuple, we didn’t even have to name them. Since both the tuple we actually returned, and the tuple claimed would be returned in the function prototype were both of type (String, Int), the Swift compiler had no issue with it. If you didn’t want to name them in the function prototype, that is okay as well, you just have to state the types, so stating the return type specifically as ” (String, Int) ” is also acceptable to the Swift compiler.
If you want to optionally return a tuple, you would just add a question mark after the return type like so:
func maybeGetHighScore() -> (String, Int)? { return nil }
Of course, what you then get back is an optional, so you will have to unwrap it to use the values now. You could do so via optional binding like so:
if let possibleScore = maybeGetHighScore() { _ = possibleScore.0 _ = possibleScore.1 } else { print("Nothing Here") }
If you want to learn a bit more about Swift Optionals, check out my previous post Swift Optionals – Declaration, Unwrapping, and Binding.
One more interesting thing to note about Tuples and functions, when you have a function that specifies no return value, it actually returns an empty tuple, which is denoted simply as ” () “, just an open and then close parenthesis (ignore the quotes, they were just to box the symbol to make it more obvious in this post).
Access Control and Tuples
Since my posts have been predominantly for illustrating parts of the Swift language and not full blown tutorials (but that will change soon), we haven’t talked too much about access control since my initial post Access Control in Swift. When we do get into tutorials, expect to see them a lot more often.
Nonetheless, they do affect Swift’s tuples as well. A tuple’s access level is determined by its constituents, and is not set directly like you would for a property or function. A tuple’s access level will be that of its most restrictive component. So if one type is private, and the other is public, the tuple’s access control will be private.
A Tuple is a Value Type
Update: Thanks to a helpful Clang developer, I have been pointed back to a post on Apple’s Swift Blog: Value and Reference Types – Swift Blog – Apple Developer, which does list the Tuple as a value type, alongside struct and enum.
Before I was reminded of the above, I did a test in a playground to see whether it treated a tuple as a value type or not:
var someScore = ("John", 55) var anotherScore = someScore anotherScore.0 = "Robert" print(anotherScore.0) //Outputs: "Robert" print(someScore.0) //Outputs: "John"
The test does pretty conclusively show that Tuples are value types. I assigned someScore to another variable named “anotherScore”. I then changed the value for the name in anotherScore to “Robert”. When I checked what anotherScore’s name was, it of course said “Robert”, but when I checked someScore (the original one) for what name it had, it still had “John”.
Conclusion
Now you have a good reference about everything Tuple. These bits were spread around Apple’s iBook originally, so you would have to go to the sections about tuples themselves for the first part, functions for the next part, and access control for the final part. It did make sense for them to be in each of those sections, but since we have already talked about those components on this blog previously, we could just round them all up into a single page.
I also wanted to thank Gavin Wiggins (@wigging on Twitter) for an update to the introduction. I had not explicitly described the tuple as a compound type, which is stated in the Language Reference part near the end of Apple’s iBook, and he rightfully said that should be clarified.
I did digress a bit about the pronunciation at the beginning, but I found it interesting and thought I would share. Pronounce it however you like, but don’t disparage somebody for pronouncing it the other way, because apparently they’re both acceptable. To me though, this post was all about too-puhls.
To follow up a bit on what I mentioned in the Access Control section of this post, I am planning on writing more tutorial style posts eventually. I wanted to cover the more general concepts first to have a starting point, but then I would eventually move into doing tutorials.
If you look at some of my Objective-C posts, I did mini-tutorials about how to do certain things like Replace Keyboard with UIDatePicker and Add sharing to your app via UIActivityViewController, and you can expect to see similar posts in Swift. It may be about specific classes like UIActivityViewController there, or it may be a more general post that puts a few different parts together like the keyboard replacing one. Making some mini-apps to demonstrate other aspects of programming for iOS in Swift is also on the horizon. I won’t say how soon you will start seeing these kind of posts (or videos perhaps). They could come out next week, or in a few months, but they are coming. Update: Actually, some have come by now, such as Add sharing to your Swift app via UIActivityViewController, How to write a WatchKit Counter App in Swift, and Hello World! Your first iOS App in Swift.
I hope you found this article helpful. If you did, please don’t hesitate to share this post on Twitter or your social media of choice, every share helps. Of course, if you have any questions, don’t hesitate to contact me on the Contact Page, or on Twitter @CodingExplorer, and I’ll see what I can do. Thanks!