在Swift中使用一个可选的值

在阅读Swift编程语言时 ,我遇到了这个片段:

您可以使用iflet来处理可能丢失的值。 这些值表示为可选项 。 一个可选值包含一个值或者包含nil来表示缺失值。 在值的types后面写一个问号(?),将该值标记为可选。

// Snippet #1 var optionalString: String? = "Hello" optionalString == nil // Snippet #2 var optionalName: String? = "John Appleseed" var greeting = "Hello!" if let name = optionalName { greeting = "Hello, \(name)" } 

代码片段#1已经足够清楚,但代码片段#2中发生了什么? 有人可以分解并解释吗? 这只是使用if - else块的替代方法吗? 在这种情况下,确切的作用是什么?

我看了这个页面,但还是有点困惑。

 if let name = optionalName { greeting = "Hello, \(name)" } 

这有两点:

  1. 它检查optionalName是否有值

  2. 如果是这样的话,它将“解开”该值并将其分配给名为String的string(仅在条件块内部可用)。

请注意, name的types是String (不是String? )。

没有let (即只是if optionalName ),它仍然会进入块只有有一个值,但你必须手动/显式访问string作为optionalName!

 // this line declares the variable optionalName which as a String optional which can contain either nil or a string. //We have it store a string here var optionalName: String? = "John Appleseed" //this sets a variable greeting to hello. It is implicity a String. It is not an optional so it can never be nil var greeting = "Hello!" //now lets split this into two lines to make it easier. the first just copies optionalName into name. name is now a String optional as well. let name = optionalName //now this line checks if name is nil or has a value. if it has a value it executes the if block. //You can only do this check on optionals. If you try using greeting in an if condition you will get an error if name{ greeting = "Hello, \(name)" } 

String? 是一个盒装types,variablesoptionalName或者包含一个String值或者什么也不包含(即nil )。

if let name = optionalName是一个习惯用法,它会将值从optionalName name取出并分配给name 。 同时,如果名称非零,则执行if分支,否则执行else分支。