Swift 中两个可选语法之间的区别
Difference between two optional syntaxes in Swift
有什么区别
self?.profile!.id!
和
(self?.profile!.id!)!
XCode 将第一个转换为第二个。
第一个包含 self?
,这意味着 self
是可选的,导致让相关属性(在您的情况下为 profile!.id!
)与 self
的存在相关这是 Optional Chaining:
Optional chaining is a process for querying and calling properties,
methods, and subscripts on an optional that might currently be nil. If
the optional contains a value, the property, method, or subscript call
succeeds; if the optional is nil, the property, method, or subscript
call returns nil
. Multiple queries can be chained together, and the
entire chain fails gracefully if any link in the chain is nil.
为了更简单,你可以想到id!
nullity也是可选的,即使你强制展开它,因为它关系到self
的存在;如果 self
是 nil
,profile
和 id
也将是 nil
隐式,因为它们与 self
.[=32 的存在有关=]
提及:(self?.profile!.id!)!
意味着整个链的价值将被强制包裹。
注意实现:
self!.profile!.id!
导致与
相同的输出
(self?.profile!.id!)!
因为 self!
是强制展开的,所以 id
的值与 self
的无效性无关,因为编译器假定 self
总是有一个值。
但是,这种方法不安全,您应该使用可选绑定。
首先你用的问号和感叹号太多了!!!
实际上没有区别。结果是一个强制展开的可选。
通常 Xcode 建议语法如果链接的最后一项的结果是非可选的,那么感叹号会导致错误,例如
text?.count!
然后Xcode建议
(text?.count)!
但在这种情况下要勇敢并写
text!.count
self?.profile!.id!
和
(self?.profile!.id!)!
XCode 将第一个转换为第二个。
第一个包含 self?
,这意味着 self
是可选的,导致让相关属性(在您的情况下为 profile!.id!
)与 self
的存在相关这是 Optional Chaining:
Optional chaining is a process for querying and calling properties, methods, and subscripts on an optional that might currently be nil. If the optional contains a value, the property, method, or subscript call succeeds; if the optional is nil, the property, method, or subscript call returns
nil
. Multiple queries can be chained together, and the entire chain fails gracefully if any link in the chain is nil.
为了更简单,你可以想到id!
nullity也是可选的,即使你强制展开它,因为它关系到self
的存在;如果 self
是 nil
,profile
和 id
也将是 nil
隐式,因为它们与 self
.[=32 的存在有关=]
提及:(self?.profile!.id!)!
意味着整个链的价值将被强制包裹。
注意实现:
self!.profile!.id!
导致与
相同的输出(self?.profile!.id!)!
因为 self!
是强制展开的,所以 id
的值与 self
的无效性无关,因为编译器假定 self
总是有一个值。
但是,这种方法不安全,您应该使用可选绑定。
首先你用的问号和感叹号太多了!!!
实际上没有区别。结果是一个强制展开的可选。
通常 Xcode 建议语法如果链接的最后一项的结果是非可选的,那么感叹号会导致错误,例如
text?.count!
然后Xcode建议
(text?.count)!
但在这种情况下要勇敢并写
text!.count