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.
SAVE 50% To celebrate WWDC23, all our books and bundles are half price, so you can take your Swift knowledge further without spending big! Get the Swift Power Pack to build your iOS career faster, get the Swift Platform Pack to builds apps for macOS, watchOS, and beyond, or get the Swift Plus Pack to learn advanced design patterns, testing skills, and more.
Link copied to your pasteboard.