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交流讨论论坛论坛:http://www.cocoagame.net
欢迎加入Swift技术交流群:362298485
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步