someFunction(completion: { [weak self] in
self?.variable = self!.otherVariable
})
这里安全吗?我在语句开头访问可选的self
,我个人认为,如果self
是nil
,则永远不会执行该语句的第二部分.这是真的吗?如果self
真的是nil
,那么第二部分就永远不会发生了?在这一行代码中,self
个可能会被"nilled"吗?
someFunction(completion: { [weak self] in
self?.variable = self!.otherVariable
})
这里安全吗?我在语句开头访问可选的self
,我个人认为,如果self
是nil
,则永远不会执行该语句的第二部分.这是真的吗?如果self
真的是nil
,那么第二部分就永远不会发生了?在这一行代码中,self
个可能会被"nilled"吗?
let john = Person() // ... let someAddress = Address() // ... john.residence?.address = someAddress
然后是(加上强调):
在本例中,try 设置john的address属性.居住将失败,因为约翰.目前居住区为零.
分配是可选链接的一部分,也就是none of the code on the right hand side of the = operator is evaluated.
适用于你的情况:在
self?.variable = self!.otherVariable
如果self
为nil
,则右侧为not.
如果self真的为零,那么第二部分就永远不会发生了?
答案是"是".关于第二个问题
在这一行代码中,self永远不会被"nilled"吗?
我最初的assumption是,一旦self
被确定为!= nil
,
This isn't guaranteed. Releases may be optimized to happen earlier than this, to any point after the last formal use of the strong reference. Since the strong reference loaded in order to evaluate the left-hand side
weakProperty?.variable
is not used afterward, there is nothing keeping it alive, so it could be immediately released.
If there are any side effects in the getter for variable that cause the object referenced byweakProperty
to be deallocated, nil-ing out the weak reference, then that would cause the force-unwrap on the right side to fail. You should use if let to test the weak reference, and reference the strong reference bound by theif let