S(tuple)類及可選(Optional)類型型
元組將多個值組合為單個值。元組內的值可以是任意 類型,各元素不必是相同的類型。元組在作為函數返 回值時尤其有用。
1、定義方法1
let http404Error= (404,"Not Found")
println("The status codeis \(http404Error.0)")
// prints "The status codeis 404"
println("The statusmessage is \(http404Error.1)")
// prints "The status message isNot Found"
2、定義方法2
let http200Status = (statusCode: 200, description: "OK")
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交流討論論壇論壇:https://www.cocoagame.net
歡迎加入Swift技術交流群:362298485
最後更新:2017-04-03 07:57:07