Tuples

Overview

Tuples enable you to create and pass around groupings of values. You can use a tuple to return multiple values from a function as a single compound value. (Swift.org)

(firstName: String, lastName: String)

Sample Codes

Example 1

func getUser() -> (firstName: String, lastName: String) {
    (firstName: "Taylor", lastName: "Swift")
}

// Long version
//let user = getUser()
//let firstName = user.firstName
//let lastName = user.lastName
//print("Name: \(firstName) \(lastName)")

// Short version
//let (firstName, lastName) = getUser()
//print("Name: \(firstName) \(lastName)")

// If you want to use only one field you should use "_" instead of that field
let (firstName, _) = getUser()
print("Name: \(firstName)")

Arrays, Sets, Tuples... When to use which?

Type
Allows Duplicates
Ordered
Multiline String
Can Grow?
Best for

Array

Yes

Yes

?

Yes

Score List by User,

Set

No

No

?

?

Dictionary,

Tuple

Yes

No?

Yes

No

Forms,

Sources

Videos

Articles / Documents

Last updated