S(tuple)類及可選(Optional)類型型

元組將多個值組合爲單個值。元組內的值能夠是任意 類型,各元素沒必要是相同的類型。元組在做爲函數返 回值時尤爲有用。函數

 

1、定義方法1spa

 

 

 

 

let http404Error= (404,"Not Found").net

 

 

 

 

println("The status codeis \(http404Error.0)")code

// prints "The status codeis 404"orm

 

 

println("The statusmessage is \(http404Error.1)")server

 

 

// prints "The status message isNot Found"ip

 

 

 

 

 

 

 

2、定義方法2it

 

 

 

 

let http200Status = (statusCode: 200, description: "OK")io

 

 

 

println("The          status          code           is變量

 

\(http200Status.statusCode)")

 

 

// prints "The status codeis 200"

 

 

println("The         status         message           is

 

\(http200Status.description)")

 

 

// prints "The status message isOK"

 

 

 

 

可選(Optional)類型

 

 

使用可選類型

 

咱們在以下狀況下使用可選類型:


•   它有值但不肯定

 

•   沒有任何值

 

let possibleNumber = "123" //Hello

 

let convertedNumber : Int? = possibleNumber.toInt()"Int?"是可選類型

 

 

 

if convertedNumber {

 

println("\(possibleNumber) has an integer value of

 

\(convertedNumber!)")

 

} else {

 

println("\(possibleNumber) could not be convertedtoan integer")

 

}

 

convertedNumber!是從可選類型中取值。

 

 

使用 nil

 

咱們能夠爲可選類選的變量設置 nil 值,表示沒有任何 值。

 

 

 

 

var serverResponseCode: Int? = 404

 

 

// serverResponseCode contains an actual Int value of

404

 

 

serverResponseCode = nil

 

 

// serverResponseCode now containswift元組

no value

 Swift交流討論論壇論壇:http://www.cocoagame.net歡迎加入Swift技術交流羣:362298485

相關文章
相關標籤/搜索