Optional chaining used in left side of assignment in Swift

∥☆過路亽.° 提交于 2019-12-10 15:15:03

问题


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?

e.g.

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

回答1:


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.

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.




回答2:


For the sake of completeness, in addition to @gregheo answer:

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.

Quoted from "Optional-Chaining Expression"




回答3:


It will just act as an optional, you can set it as a string or nil. Neither of them will crash the app unless you unwrap your variable without catching if it is nil, when it is nil. If anything in your chain is an optional, your whole chain is (or at least everything after the optional)



来源:https://stackoverflow.com/questions/29221293/optional-chaining-used-in-left-side-of-assignment-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!