Swift中分配左侧使用的可选链接 [英] Optional chaining used in left side of assignment in Swift
问题描述
在赋值语句的左侧使用可选链接是什么意思?如果可选变量为nil,应用程序是否会崩溃?
What does it mean when optional chaining is used in the left side of the assignment statement? Will the app crash if the optional variable is nil?
例如
// cell is a UITableViewCell
cell.textLabel?.text = "Test"
推荐答案
类似于短路的&&
运算符的排序在到达第一个false值时停止,而可选链在达到第一个nil值时将停止.
Sort of like a short-circuiting &&
operator that stops when it reaches the first false value, optional chaining will stop when it hits the first nil value.
因此,在像container?.cell?.textLabel?.text = "foo"
这样的极端情况下,容器,单元格或textLabel中的任何一个都可能为零.如果它们中的任何一个是有效的,则该声明实际上是无操作的.仅当整个链为非零时,分配才会发生.
So in an extreme case like container?.cell?.textLabel?.text = "foo"
, any of container, cell, or textLabel could be nil. If any of them are, that statement is effectively a no-op. Only if the whole chain is non-nil will the assignment happen.
这篇关于Swift中分配左侧使用的可选链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!