如何知道可选链接在哪里中断? [英] How to know where Optional Chaining is breaking?

查看:81
本文介绍了如何知道可选链接在哪里中断?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,在iOS Swift中,我们可以像

So in iOS Swift we can do optional chaining to simplify the nil checking like in the official documentation

let johnsAddress = Address()
johnsAddress.buildingName = "The Larches"
johnsAddress.street = "Laurel Street"
john.residence!.address = johnsAddress
if let johnsStreet = john.residence?.address?.street {
    println("John's street name is \(johnsStreet).")
} else {
    println("Unable to retrieve the address.")
}
// prints "John's street name is Laurel Street."

我了解john.residence?.address?.street中可选链的用法,但是我们怎么知道链在哪里断开(如果residenceaddressnil).是否可以确定residenceaddressnil,还是需要再次使用if-else进行检查?

I understand about the usage of the optional chaining in john.residence?.address?.street but how can we know where is actually the chain is breaking (if either residence or address is nil). Can we determine if residence or address is nil, or we need to check it again with if-else?

推荐答案

然后不要进行链接.仅当您不想停止时,链条才会有趣.如果这样做的话,请在有趣的地方将其分解-否则,您将在哪里放置坏情况代码?

Don't do the chain then. The chain is only interesting if you don't intend to stop. If you do, break it up at interesting spots - otherwise, where would you put in the code for the bad cases?

if let residence = john.residence {
  if let address = residence.address {
    ...
  } else {
    println("missing address")
  }
} else {
  println("missing residence")
}

这篇关于如何知道可选链接在哪里中断?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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