iOS Tuples - toant-dev/toandev.github.io GitHub Wiki

What is Tuples?

Tuples in Swift occupy the space between dictionaries and structures: they hold very specific types of data (like a struct) but can be created on the fly (like dictionaries). They are commonly used to return multiple values from a function call.

let person = (name: "Paul", age: 35)
func split(name: String) -> (firstName: String, lastName: String) {
    let split = name.components(separatedBy: " ")
    return (split[0], split[1])
}

let parts = split(name: "Paul Hudson")
parts.0
parts.1
parts.firstName
parts.lastName

Special examples

  • Swap values without intermedia variable
func swap<T>( _ a: inout T, _ b: inout T) {
  (a, b) = (b, a)
}

swap(&dog, &cat)