someFunction(completion: { [weak self] in
    self?.variable = self!.otherVariable
})

这里安全吗?我在语句开头访问可选的self,我个人认为,如果selfnil,则永远不会执行该语句的第二部分.这是真的吗?如果self真的是nil,那么第二部分就永远不会发生了?在这一行代码中,self个可能会被"nilled"吗?

推荐答案

Optional Chaining

 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

如果selfnil,则右侧为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 by weakProperty 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 the if let

Swift相关问答推荐

启用完成并发判断以及如何解决警告(续)

如何在自定义视图中读取修改符子元素?

是否在字符串属性上搜索数组和子数组?

SWIFT异步/等待,多个监听程序

Swift图表';chartXVisibleDomain挂起或崩溃

在扩展中创建通用排序函数

如何在设备(或常量)地址空间中创建缓冲区?

如何隐藏集合视图中特定的单元格,以避免出现空白空间?

在Swift中如何用变量计算0.9的立方

如何使一个 Reality Composer 场景中的分组对象可拖动?

在 struct 中的序列和非序列泛型函数之间进行 Select

如何为等待函数调用添加超时

如何裁剪图像 3:4 ?迅速

为什么 Apple Scrumdinger Sample App 使用两个事实来源?

引用类型(类)不需要但 struct 需要的可识别 id

异步等待不会在项目中触发,但在 Xcode playground 中工作正常

VStack SwiftUI 中的动态内容高度

iOS 判断应用程序是否可以访问麦克风

swift : 具有类型和值的枚举常量

如何快速截取 UIView 的屏幕截图?