【问题标题】:getting "unexpectedly found nil" AFTER performing nil check在执行 nil 检查后得到“意外发现 nil”
【发布时间】:2017-04-14 18:21:30
【问题描述】:

尽管检查为零,但我收到fatal error: unexpectedly found nil while unwrapping an Optional value 错误被捕获在条件中(下面的第一行)

if (obj.prop != nil && obj.prop?.otherprop != nil) {
    anotherObj.yetanotherprop = (obj.prop?.otherprop as NSURL).absoluteString
}

我也尝试过使用if let 如下(xcode 突出显示第二个 let 是发现意外 nil 的位置):

if let objA = obj.prop,
    let otherProp = objA.otherPROP {
    anotherObj.yetanotherprop = (otherProp as NSURL).absoluteString
}

为什么这些都不行?!

我正在从以目标 c 编写的第 3 方库中获取源对象(在上述两种情况下均为obj)。我怀疑我以某种方式检查 nil 错误?

【问题讨论】:

  • 您使用的是什么第三方库?
  • 我无法讨论第三方库,但我通过 realmswift 将这些对象本地存储在领域数据库中

标签: swift swift2


【解决方案1】:

所以在写这篇文章时,我想我有点想通了。我不知道为什么第一个不起作用,但第二个起作用:

if let objA = obj.prop,
    let otherProp = objA?.otherPROP {
    anotherObj.yetanotherprop = (otherProp as NSURL).absoluteString
}

【讨论】:

  • 检查 Obj.prop 的类型。它有两个问号吗?像 - “字符串??”例如
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多