Swift学习2--可选类型optional

定义

optional表明前面的变量能否为空
Swift中声明的一个变量时, 默认情况下它是non-optional的, 即必须赋予这个变量一个非空的值. 如果给non-optional类型的变量赋值nil, 编译器就会报错。Nil cannot be assigned to type ‘xxx’

为何引入可选类型

在OC中,可能因为在运行阶段,将nil参数传入系统函数中而导致崩溃。swift增强了这种检查,对于不能为空的参数,在编译阶段就进行检查,可能为空时编译报错。例如:

func findStockCode(company: String) -> String? {
if (company == “Apple”) {
return “AAPL”
} else if (company == “Google”) {
return “GOOG”
}
return nil
}
var stockCode:String? = findStockCode(“Facebook”)
let text = “Stock Code - ”
let message = text + stockCode // compile-time error
print(message)

编译报错:可选类型的值没有被解包: value of optional type String? is not unwrapped

解包可选类型(Unwrapping Optionals)

方法1:硬解包

var stockCode:String? = findStockCode(“Facebook”)
let text = “Stock Code - ”
if stockCode {
let message = text + stockCode!
print(message)
}

方法2:可选绑定(Optional Binding)

与硬解包不同, 可选绑定(Optional Binding)是一种更简单更推荐的方法来解包一个可选类型. 使用可选绑定来检查可选类型的变量有值还是没值. 如果有值, 解包它并且将值传递给一个常量或者变量.
if let或者if var`是可选绑定的两个关键字

var stockCode:String? = findStockCode(“Facebook”)
let text = “Stock Code - ”
if let tempStockCode = stockCode {
let message = text + tempStockCode
print(message)
}

可选链式调用(Optional Chaining)

对于多个层次的if let / if var,可以使用?.连接多个可选类型。
class Stock {
var code: String?
var price: Double?
}
func findStockCode(company: String) -> Stock? {
if (company == “Apple”) {
let aapl: Stock = Stock()
aapl.code = “AAPL”
aapl.price = 90.32
return aapl
} else if (company == “Google”) {
let goog: Stock = Stock()
goog.code = “GOOG”
goog.price = 556.36
return goog
}
return nil
}

计算买100股所需的价格:
if let stock = findStockCode(“Apple”) {
if let sharePrice = stock.price {
let totalCost = sharePrice * 100
print(totalCost)
}
}

使用可选链式调用:
if let sharePrice = findStockCode(“Apple”)?.price {
let totalCost = sharePrice * 100
print(totalCost)
}

参考:
http://www.cocoachina.com/swift/20160810/17330.html

你可能感兴趣的:(iOS-Swift)