在
“The Swift Programming Language.”书中,Apple提到在访问可选变量时使用if和let.
本书给出了以下代码:
var optionalString: String? = "Hello" optionalString == nil var optionalName: String? = "John Appleseed" var greeting = "Hello!" if let name = optionalName { greeting = "Hello,\(name)" }
使用if name = optionalName,而不是optionalName!= nil(并始终将其称为,optionalName),有什么好处?有什么区别,还是仅仅是惯例?
因为它还解包了可选值,所以这段代码:
原文链接:https://www.f2er.com/swift/320022.htmlif let name = optionalName { greeting = "Hello,\(name)" }
相当于:
if optionalName != nil { let name:String = optionalName! greeting = "Hello,\(name)" }
这种语言糖在Swift中被称为Optional Binding.
可选类型
在Swift T和T?是不是相同的类型,但可选T的基础值?类型可以很容易地实现使用!后缀运算符,例如:
let name:String = optionalName!
现在可以在需要String的地方使用,例如:
func greet(name:String) -> String { return "Hello,\(name)" } greet(name)
虽然这样做是安全的,但Swift确实允许你隐式转换为可选类型:
let name = "World" let optionalName: String? = name func greet(optionalName:String?) -> String? { if optionalName != nil { return "Hello,\(optionalName)" } return nil } //Can call with either String or String? greet(optionalName) greet(name)