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 ViRE offers discoverable way of working with regex. It provides really readable regex experience, code complete & cheat sheet, unit tests, powerful replace system, step-by-step search & replace, regex visual scheme, regex history & playground. ViRE is available on Mac & iPad.
Sponsor Hacking with Swift and reach the world's largest Swift community!
Link copied to your pasteboard.