Tuple is a new data type in Swift. It can group multiple values of different type of data into a single tuple. It is useful when you want to return multiple values in a function.
There is an example in the Swift document from Apple, you can give elements a name when you create the tuple.
let http200Status = (statusCode: 200, description: "OK")
println("The status code is \(http200Status.statusCode)")
// prints "The status code is 200"
println("The status message is \(http200Status.description)")
// prints "The status message is OK"
The element name makes the code more readable and meaningful. However, the name can only be used within the scope. If you get a tuple that returned from a function. The element name will be removed. The element can be gotten by index number of the element.
func getHttp200Status() -> (Int, String) {
let http200Status = (statusCode: 200, description: "OK")
return http200Status
}
var status = getHttp200Status()
println("The status code is \(http200Status.statusCode)")
// '(Int, String)' does not have a member named 'statusCode'
println("The status code is \(http200Status.0)")
Elements are numbered from 0 and autocomplete will tell you what is inside the tuple.
Tuple是Swift的新資料類型. 它可以把多個不同資料類型的值組合在一個tuple內. 當你想function回傳多個值時, 這個會很有用.
這裡有一個範例在Apple的Swift文件. 當創建一個tuple時, 你可以給予每一個元素一個名字.
let http200Status = (statusCode: 200, description: "OK")
println("The status code is \(http200Status.statusCode)")
// prints "The status code is 200"
println("The status message is \(http200Status.description)")
// prints "The status message is OK"
這個名字能令你的code可讀性更高及更有意思. 不過, 這個名字只可以在scope內使用. 如果你由一個function取得一個tuple, 元素的名字會被移除. 而元素仍能以索引數字取得.
func getHttp200Status() -> (Int, String) {
let http200Status = (statusCode: 200, description: "OK")
return http200Status
}
var status = getHttp200Status()
println("The status code is \(http200Status.statusCode)")
// '(Int, String)' does not have a member named 'statusCode'
println("The status code is \(http200Status.0)")
元素索引由0開始, 自動完成會告訴你有甚麼元素在tuple裡.