Swift學習——Swift基礎詳解(五)

來源:互聯網
上載者:User

標籤:swift基礎   swift   元組   

上回書說道:灰常灰常基本的資料類型

下面咱們來點進階的:


Tuples    元組

元組儲存一對鍵值,並且沒有類型限制

let http404Error = (404, "Not Found")// http404Error is of type (Int, String), and equals (404, "Not Found")
書上廢話一堆,反正元組就是這麼寫,上面的例子還是(Int,String)類型的元組,而且元組裡面的類型隨便你定義

也可以將元組的變數分離:

let (statusCode, statusMessage) = http404Errorprintln("The status code is \(statusCode)")// prints "The status code is 404"println("The status message is \(statusMessage)")// prints "The status message is Not Found
如果你只需要元組中的部分值,可以使用底線將不需要的值代替:

let (justTheStatusCode, _) = http404Errorprintln("The status code is \(justTheStatusCode)")// prints "The status code is 404
也可以使用索引擷取元組中的值:

println("The status code is \(http404Error.0)")// prints "The status code is 404"println("The status message is \(http404Error.1)")// prints "The status message is Not Found
在元組定義的時候,可以命名元組中的值,這樣就可以用值的名稱擷取值了:

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
對了,元組的一個非常有用的地方就是它可以作為函數的返回值,在之前的文章介紹過,Swift中的函數可以有多個返回值。

還有就是,元組不適合複雜的資料群組合,如果資料太複雜,還是使用類或者結構體吧。




相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.