Swift Tuple Explained

Swift Tuple Explained


Think of a Tuple as a bespoke collection of values. To define a Tuple, you wrap the comma-separated selection of values in parentheses.

Tuples are useful when you want to return multiple values from a function or group related values together without needing to define a custom structure or class. Each element in a tuple can be of a different type.



let user = ("Jane Doe", 1974, true)

print(user) // ("Jane Doe", 1974, true)        

In this code, the variable named user is a Tuple containing three elements, a String (“Jane Doe”), an Int (1974), and a Bool (true).



let user: (String, Int, Bool) = ("Jane Doe", 1974, true)

print(user) // ("Jane Doe", 1974, true)        

Like any other type, you can declare a Tuple with type annotation for clarity about the kind of values that the Tuple can contain. To do this, you place a colon after the variable or constant name, followed by the value types wrapped in parentheses, followed by the assignment operator and followed by the Tuple.



let user = ("Jane Doe", 1974, true)

print(user.0) // Jane Doe
print(user.1) // 1974
print(user.2) // true        

You can access the individual values of a Tuple by using a zero-based index.



let user = (name: "Jane Doe", DOB: 1974, female: true)

print(user.name) // Jane Doe
print(user.DOB) // 1974
print(user.female) // true        

You can assign names to the individual values of a Tuple so that they are easier to access.



func user() -> (name: String, DOB: Int, female: Bool) {
    
    return ("Jane Doe", 1974, true)
}

let myUser = user()

print(myUser) // (name: "Jane Doe", DOB: 1974, female: true)        

You can also return a Tuple from a function.



let user = ("Jane Doe", 1974, true)

let (name, DOB, isFemale) = user

print(name) // Jane Doe
print(DOB) // 1974
print(isFemale) // true        

Decomposing a Tuple is a great way to access the elements as individual variables.



let user = ("Jane Doe", 1974, true)

let (name, _, _) = user

print(name) // Jane Doe        

To ignore or silence one of the assigned values, simply replace it with an underscore.



Lastly, remember that Tuples are useful for temporary groupings of multi-type values, so keep them small and lightweight!

Max Barker

Hire FAANG talent on Discord | Used by top VC backed startups | Send me a DM for access ???

1 周

要查看或添加评论,请登录