Tutorial by Examples

Tuples group multiple values into a single compound value. The values within a tuple can be of any type and do not have to be of the same type as each other. Tuples are created by grouping any amount of values: let tuple = ("one", 2, "three") // Values are read using index n...
Tuples can be decomposed into individual variables with the following syntax: let myTuple = (name: "Some Name", age: 26) let (first, second) = myTuple print(first) // "Some Name" print(second) // 26 This syntax can be used regardless of if the tuple has unnamed properti...
Functions can return tuples: func tupleReturner() -> (Int, String) { return (3, "Hello") } let myTuple = tupleReturner() print(myTuple.0) // 3 print(myTuple.1) // "Hello" If you assign parameter names, they can be used from the return value: func tupleReturner(...
Occasionally you may want to use the same tuple type in multiple places throughout your code. This can quickly get messy, especially if your tuple is complex: // Define a circle tuple by its center point and radius let unitCircle: (center: (x: CGFloat, y: CGFloat), radius: CGFloat) = ((0.0, 0.0), ...
Tuples are useful to swap values between 2 (or more) variables without using temporary variables. Example with 2 variables Given 2 variables var a = "Marty McFly" var b = "Emmett Brown" we can easily swap the values (a, b) = (b, a) Result: print(a) // "Emmett Bro...
Use tuples in a switch let switchTuple = (firstCase: true, secondCase: false) switch switchTuple { case (true, false): // do something case (true, true): // do something case (false, true): // do something case (false, false): // do something } Or in combina...

Page 1 of 1