Swift學習之六 元組(Tuples)

2021-06-22 09:28:17 字數 1163 閱讀 6249

元組是多個值組合而成的復合值。元組中的值可以是任意型別,而且每乙個元素的型別可以是不同的。

如:

// http404error是(int, string)型別

// 這個元組是二元組,是乙個整型和字串型別的組合,這裡代表著404的意思是not found

元組是可以分解的。

如:

let (statuscode, statusmessage) = http404error

// prints "the status code is 404"

println("the status code is \(statuscode)")

println("the status message is \(statusmessage)")

元組在分解時,可以只分解部分值,而忽略其它值,忽略其它值可以用下劃線_來代替.

如:

let (statuscode, _) = http404error

println("the status code is \(statuscode)")

訪問元組的另外一種方式:通過下標獲取,從0開始

如:

let http404error = (404, "not found")

// 通過元組.0獲取第二個值

// 通過元組.1獲取第二個值

訪問元組元素還有一種方式:給定元組元素命名,然後通過名稱獲取值(元組.名稱)

如:

let http200status = (statuscode: 200, description: "ok")

swift學習02 元組tuple

元組tuple lettuple errostring 錯誤資訊 errortype 404 vartuplevar errorstring 錯誤資訊 errortype 404 vartuplevar 錯誤資訊 404 tuple 可以把多個值組合成乙個復合值。tuple 可以是任意型別,不用相同...

Swift語法09 元組

使用元祖描述乙個人的資訊 1001 張三 30,90 給元素加上元素名稱,之後可以通過元素名稱訪問元素 id 1001 name 張三 english score 30,chinese score 90 元組 http錯誤 let array 404,not found 寫法一 let error ...

六 元組與字典

我們今天來認識兩種新的資料型別 元組和字典。字串拼接符 兩個字串之間,要把它們合二為一。我們可以這樣寫 print 123 456 輸出 123456直接使用 將兩個字串加到一起就可以了。認識元組 元組與列表近似,是由小括號 組成的,將資料括在中間,能儲存無數個資料,獲取方法也與列表相同,甚至連迴圈...