Tuple in Swift

This article explains what a Tuple is and when and where it is used. Happy reading!!!

pic credit: Stocksnap.io
var person = ("John", "Smith")

var firstName = person.0 // John
var lastName = person.1 // Smith

Creating a tuple:

var point = (0, 0)

point.0 = 10
point.1 = 15

point // (10, 15)
var origin = (x: 0, y: 0)

var point = origin
point.x = 3
point.y = 5

print(origin) // (0, 0)
print(point) // (3, 5)

Named elements:

var person = (firstName: "John", lastName: "Smith")var firstName = person.firstName // John
var lastName = person.lastName // Smith

Multiple assignment:

var (a, b, c) = (1, 2, 3)

Returning multiple values:

Tuples for iterating a dictionary getting both key and value:

for (key,value) in myDictionary {  println("My key is \(key) and it has a value of \(value)")}
for (key,_) in myDictionary {println("My key is \(key)")
}

Decomposing Tuples:


let http404Error = (404, "Not Found")
// http404Error is of type (Int, String), and equals (404, "Not Found")
let (statusCode, statusMessage) = http404Errorprint("The status code is \(statusCode)")// Prints "The status code is 404"print("The status message is \(statusMessage)")// Prints "The status message is Not Found"
let (justTheStatusCode, _) = http404Errorprint("The status code is \(justTheStatusCode)")// Prints "The status code is 404"
print("The status code is \(http404Error.0)")// Prints "The status code is 404"print("The status message is \(http404Error.1)")// Prints "The status message is Not Found"
let http200Status = (statusCode: 200, description: "OK")

A tuple inside another tuple:

let bar: (Int, (Bool, String)) = (1, (false, "Hello"))print(bar.0) // print: “1”print(bar.1.0) // print: “false”print(bar.1.1) // print: “Hello”

An easy way of swapping two values:

var a = 5 
var b = 4
(b, a) = (a, b)

Where to use tuples

That’s it. !

If you enjoyed reading this post, please share and give some clapps so others can find it 👏👏👏👏👏 !!!!

iOS and tvOS developer, dreamer, photographer 🤨