Tuples can be used to return multiple values from Swift functions. A tuple allows you to group together multiple values of different types which can then be returned from a function as a single entity.
Here is an example of a function which returns a String, an Int and a Double:
func returnMultipleValues() -> (String, Int, Double) {
return ("Swift Tuple", 12, 3.14)
}
Here is how to access the individual values from a return tuple by using their respective indexes:
let result = returnMultipleValues()
let nameString = result.0
let intValue = result.1
let doubleValue = result.2
Instead of accessing tuple values by index, tuple elements can be named in function definition which greatly enhances code readability:
func returnMultipleValues() -> (name: String, count: Int) {
return ("Simple Swift Guide", 51)
}
Accessing the individual tuple values becomes much cleaner:
let result = returnMultipleValues()
let name = result.name
let count = result.count
Returning optionals
Entire tuple can be made an optional return value:
func returnMultipleValues() -> (name: String, count: Int)? {
if condition {
return nil
}
return ("Simple Swift Guide", 51)
}
if let result = returnMultipleValues() {
let name = result.name
let count = result.count
}
Each individual element of a tuple can be made optional. For example, a name element is made optional:
func returnMultipleValues() -> (name: String?, count: Int)
Related tutorials:
- How to use tuples in Swift
- How to use switch statement with enum in Swift
- How to pick a random element from an array in Swift