Use Tuples as Function Return Types in Swift
Written by Team Kodeco
Written by Team Kodeco
In Swift, you can use tuples as the return type of a function. This allows a function to return multiple values at once.
Here’s an example of how to create a function that returns a tuple:
func getTuple() -> (Int, String) {
return (1, "apple")
}
let tuple = getTuple()
print(tuple.0) // 1
print(tuple.1) // "apple"
You can also use named tuples as the return type of a function:
func getNamedTuple() -> (number: Int, fruit: String) {
return (number: 1, fruit: "apple")
}
let namedTuple = getNamedTuple()
print(namedTuple.number) // 1
print(namedTuple.fruit) // "apple"
Prev chapter
4.
Use Named Tuples in Swift
Next chapter
6.
Use Tuples in Switch Statements in Swift