Swift中的元組

元組把多個值組合成一個復合值,元組內的值可以是任意類型。

let http404Eror = (404, "Not Found")
// http404Error的類型是(Int, String)

元組的內容可以分解成單獨的可使用的常量和變量:

let (statusCode, statusMessage) = http404Error
print("The status code is \(statusCode)")
print("The status message is \(statusMessage)")

如果只需要分解一部分元組值,可以用_標記要忽略的部分:

let (justTheStatusCode, _) = http404Error
print("The status code is \(justTheStatusCode)")

此外,還可以通過下標來訪問元組中的單個元素:

print("The status code is \(http404Error.0)")
print("The status code is \(http404Error.1)")

定制元組的時候可以給單個元素命名:

let http200Status = (statusCode: 200, description: "OK")
print("The status code is \(http200Status.statusCode)")
print("The status message is \(http200Status.description)")

強烈推薦給元祖的元素命名,可以使代碼更清晰。

作為函數返回值時,元組非常有用:

 func getSize() -> (statusCode: Int, description: String) {
    return (200, "OK")
 }
 
 let x = getSize()
 print("code is \(x.statusCode), descripiton is \(x.description)")
 // or
 print("code is \(getSize().statusCode), descripiton is \(getSize().description)")
 // print "code is 200, descripiton is OK"

注意:
元組在臨時組織值得時候很有用,但是并不適合創建復雜的數據結構。如果你的數據結構并不是臨時使用,請使用類或者結構體。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容