加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Swift可选链接总是使用if let构造完成,还是仅使用带有可选项的问

发布时间:2020-12-14 04:52:03 所属栏目:百科 来源:网络整理
导读:根据Apple文档,可选链接如下: You specify optional chaining by placing a question mark (?) after the optional value on which you wish to call a property,method or subscript if the optional is non-nil. … optional chaining fails gracefully w
根据Apple文档,可选链接如下:

You specify optional chaining by placing a question mark (?) after the optional value on which you wish to call a property,method or subscript if the optional is non-nil. … optional chaining fails gracefully when the optional is nil …

我对此的解释是,以下结构是可选链接:

someMasterObject.possiblyNilHandler?.handleTheSituation()

…如果处理程序不是nil,则上面的行将调用handleTheSituation方法,如果处理程序为nil,则优先失败(跳过行).

但是,我看到的可选链接的几乎所有示例都使用“if let”构造,如下所示:

if let handler = someMasterObject.possiblyNilHandler{
  handler.handleTheSituation()
}

事实上,我在网上找到的文档和示例大量使用了与可选链接相关的“if let”结构,看起来似乎是IS可选链接.

但是,我是否正确假设我的第一个示例是支持使用可选链接,并且if let构造是使用(或紧密绑定)可选链接的另一个构造?

解决方法

结论是正确的 – let是一个独立但有用的结构.在上下文中,它仅在if-body中引入绑定,并且仅在绑定值不为-nil时才执行if-body. (从技术上讲,它会解开可选的绑定.)

let不影响如何处理右边的表达式(有或没有链接).例如,如果someMasterObject是可选的/ nil,它将失败而不是“链” – 即使使用let.

当一个或另一个(或两者)更“正确”时,取决于具体情况:例如.什么是被束缚的以及纠正措施应该是什么.

例如,如果someMasterObject可能为nil,我们可能会使用以下内容同时使用chaining和let.还要注意返回值如何重要并且不是简单地丢弃或“失败时为零”:

if let handler = someMasterObject?.possiblyNilHandler{
  return handler.handleTheSituation()
} else {
  return FAILED_TO_CALL
}

然后将它与非等效的链式形式进行比较,该形式只会在失败的调用情况下返回nil,但是nil可能是来自handleTheSituation的有效返回值!

return someMasterObject?.possiblyNilHandler?.handleTheSituation()

另一方面,请考虑始终将链接直接转换为嵌套的if-let语句:

result_of_expression = someMasterObject?.possiblyNilHandle?.handleTheSituation()

if let master = someMasterObject {
   if let handler = master.possiblyNilHandler {
       result_of_expression = handler.handleTheSituation()
   } else {
       result_of_expression = nil
   }
} else {
   result_of_expression = nil
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读