天天看點

swift學習記錄(元組tuples)

元組(tuples) 

是将多個值組合成一個複合值,元組内的值可以是任意類型,各個元素不必是相同的資料類型。元組作為函數的傳回值時尤其有用。

元組的不可變與可變 取決于 修飾符 let 和 var 。let 修飾的元組 不可變,var修飾的元組可變。

定義方式1:

不給元組中的元素指定名字

let httpState1 = (true,200,"成功")
           

定義方式2:

給元組中的每個元素指定名字,也隻給其中的某個(某些)元素指定名字

let httpState2 = (success : true, code : 200, msg : "成功")
           
let httpState3 = (true, code : 200, "成功")
           

取值:

1,使用元組中的元素下标 取值,其中下标從 0 開始

let value = httpState1.2
print("value is \(value)")
//value is 成功
           

2,将元組賦給一個全是變量名組成的新的元組

let(state,code,_) = httpState1
print("state is \(state) and code is \(code)")
//state is true and code is 200
           

其中的 state 和 code  是變量名,如果元組的中的某個值不需要關系,可以使用下劃線"_"将其忽略掉。

3,當我們為元組中的元素指定了名稱時,可以使用元素的名稱通路他的值

let code = httpState2.code
let msg = httpState2.msg

print("code is \(code) and msg is \(msg)")
//code is 200 and msg is 成功