Updated for Xcode 14.2
Swift’s functions have a single return type, such as Int
or String
, but that doesn’t mean we can only return a single value. In fact, there are two ways we can send back multiple pieces of data:
(name: String, age: Int)
If you had a hard time understanding why tuples were important, this is a really good example of a place where they really stand out.
If we wanted to make a function that returns a person’s first name and last name, we could do it like this:
func getUser() -> [String] {
["Taylor", "Swift"]
}
let user = getUser()
print(user[0])
That sends back an array containing two strings and stores it in user
, which does the job. However, the code is problematic for two reasons:
A second pass at the function might look like this:
func getUser() -> [String: String] {
["first": "Taylor", "last": "Swift"]
}
let user = getUser()
print(user["first"])
That’s definitely better, because now we can be sure exactly where to find each value: user["first"]
will always be “Taylor” no matter whether we change the dictionary order or if we insert a middle name.
However, this solution still isn’t ideal:
user["First"]
will fail because we wrote “First” rather than “first”.Tuples can solve the problem by letting us be specific about what data will come back: its name, its type, its order, and whether it’s optional or not. This means we can write functions to return multiple values much more safely:
func getUser() -> (first: String, last: String) {
(first: "Taylor", last: "Swift")
}
let user = getUser()
print(user.first)
Now we’ve written code that is immune to all our problems:
So, tuples make fantastic candidates for returning multiple values from functions.
SPONSORED Play is the first native iOS design tool created for designers and engineers. You can install Play for iOS and iPad today and sign up to check out the Beta of our macOS app with SwiftUI code export. We're also hiring engineers!
Sponsor Hacking with Swift and reach the world's largest Swift community!
Link copied to your pasteboard.