- ordered list of values
- no limit to the # of items
- can be of any type, not necessarily the same (can be inferred)
- useful for temporary groups of related values
- not useful for the creation of complex data structures
Assigning
// declaration - create but don't initialize<br>
var rectangle0: (Int, Int)
// create and initialize with initial values
let rectangle1 = (200, 100)
// create and initialize with initial values and names (preferred)
var rectangle2 = (width:200, height:100)
Decomposing
// decompose with .dot syntax -> 100<br>
rectangle1.1
// decompose with name -> 200
rectangle2.width
// -> a = 200, b = 100
let (a, b) = rectangle1
let (_, e) = rectangle2
_
→ shows that you are ignoring this part for now
Decomposing from a Function
- let a variable = tuple, then reference by var names directly
// function returning a tuple
func getSongAndLength()
-> (name: String, length: Int?) {
return ("Centerfold", nil)
}
// assignment of a tuple from a function
let (name, length) = getSongAndLength()
print("The song is \(name) and it's \(length ?? 90) seconds long")
- length is an Optional (
Int?
) and can be set tonil
- assign names up front to identify tuple values and use them
??
→ Nil-Coalescing Operator – used to assign a default value for an Optional