Swift 赋值左侧使用的可选链接

Optional chaining used in left side of assignment in Swift

在赋值语句的左侧使用可选链接是什么意思?如果可选变量为 nil,应用程序会崩溃吗?

例如

// cell is a UITableViewCell
cell.textLabel?.text = "Test"

它只是一个可选的,你可以将它设置为一个字符串或nil。它们都不会使应用程序崩溃,除非你解包你的变量而不捕获它是否为 nil,当它为 nil 时。 如果你的链中有任何东西是可选的,那么你的整个链是(或者至少是可选之后的所有东西)

有点像短路 && 运算符,当它达到第一个 false 值时停止,可选链接将在它达到第一个 nil 值时停止。

所以在像container?.cell?.textLabel?.text = "foo"这样的极端情况下,容器、单元格或文本标签中的任何一个都可能为零。如果其中任何一个是,则该声明实际上是空操作。只有当整个链不为零时,分配才会发生。

为了完整起见,另外@gregheo回答:

The unwrapped value of an optional-chaining expression can be modified, either by mutating the value itself, or by assigning to one of the value’s members. If the value of the optional-chaining expression is nil, the expression on the right hand side of the assignment operator is not evaluated.

引自"Optional-Chaining Expression"