强制解包在同一行代码中可选择访问的变量是否安全? [英] Is it safe to force unwrap variables that have been optionally accessed in the same line of code?

查看:134
本文介绍了强制解包在同一行代码中可选择访问的变量是否安全?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

总是安全吗?我在语句的开头访问了可选的 self ,我个人认为如果 self c> self nil 。这是真的?如果 self 确实是 nil ,第二部分将永远不会发生?在这一行代码中, self 永远不会被'nilled'吗?

Is this always safe? I access the optional self in the beginning of the statement, and personally I assume that the second part of this statement will never be executed if self is nil. Is this true? If self indeed is nil, the second part will never happen? And it will never happen that self could be 'nilled' during this single line of code?

推荐答案

可选链接来自The Swift Programming Language的

给出了以下示例:

Optional Chaining from "The Swift Programming Language" gives the following example:


 let john = Person()
 // ...
 let someAddress = Address()
 // ...
 john.residence?.address = someAddress


后跟(强调添加):


在此示例中,尝试设置john.residence的地址属性将失败,因为john.residence目前为零。

In this example, the attempt to set the address property of john.residence will fail, because john.residence is currently nil.

赋值是可选链接的一部分,这意味着不会评估=运算符右侧的代码。

The assignment is part of the optional chaining, which means none of the code on the right hand side of the = operator is evaluated.

适用于您的情况:在

self?.variable = self!.otherVariable

右边是评估 self nil
因此你问题的答案

the right-hand side is not evaluated if self is nil. Therefore the answer to your question


如果自己确实是零,第二部分永远不会发生?

If self indeed is nil, the second part will never happen?

是是。关于第二个问题


在这一行代码中,自我可能永远不会被填充吗?

And it will never happen that self could be 'nilled' during this single line of code?

假设一旦确定 self != nil
a强烈提及 self!在整个
的评估中持有声明,这样就不会发生。 (现已确认为
dfri的回答。)

I assume that once self has been determined to be != nil, a strong reference to self! is held throughout the evaluation of the statement, so that this can not happen. (Now confirmed in dfri's answer.)

这篇关于强制解包在同一行代码中可选择访问的变量是否安全?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆