在“ Swift编程语言”中。在书中,Apple提到在访问可选变量时同时使用if和let。
if
let
本书提供以下代码作为示例:
var optionalString: String? = "Hello" optionalString == nil var optionalName: String? = "John Appleseed" var greeting = "Hello!" if let name = optionalName { greeting = "Hello, \(name)" }
使用if let name = optionalName而不是if optionalName != nil(并且始终将其称为optionalName)有什么好处?有什么区别,还是仅仅是约定?
if let name = optionalName
if optionalName != nil
optionalName
因为它也解开了可选值,所以这段代码:
if let name = optionalName { greeting = "Hello, \(name)" }
等效于:
if optionalName != nil { let name:String = optionalName! greeting = "Hello, \(name)" }
这种语言糖在Swift中被称为Optional Binding。
在Swift T和T?不是相同的类型中,但是T?可以使用!postfix运算符轻松实现可选类型的基础值,例如:
T
T?
!
let name:String = optionalName!
现在可以在String期望a的地方使用它,例如:
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)