【问题标题】:field has value confirmed but still get unwrap error?字段已确认值但仍然出现解包错误?
【发布时间】:2016-04-28 11:53:25
【问题描述】:

此代码块在尝试设置 appURL 时失败,即使 if 测试成功并且托管对象联系人的所有字段都设置为非零值,并且对于某些 contact.facebook 有一个值,所以我不明白我为什么尝试打开包装时发现为零?

func openFacebook() {

    if (contact.facebook) != nil && (contact.facebook) != "" {

        // build url to users facebook page
        let appURL = NSURL(string: String(format: "fb://profile=%@", contact.facebook!))!

        // build url to user page on facebook web site
        let webURL = NSURL(string: String(format: "http://www.facebook.com/%@", contact.facebook!))!

        openURL(appURL, webURL: webURL)
    }
}

【问题讨论】:

  • contact.facebook 返回什么?您可以使用 if let 构造安全地解开该值。
  • 经过这么长时间试图找到错误结果是因为contact.facebook在字面值中有一个空格,并且是NSURL抛出了一个不稳定的问题!立即更改代码以使用正则表达式!
  • 如果你发现问题就好了。
  • 是的,快把我逼疯了……我该如何结束这个问题……你知道吗?

标签: swift2 optional unwrap forced-unwrapping


【解决方案1】:

我建议以更好的方式来做:

func openFacebook() {

    if let contact = contact.facebook where contact != "" {

        // build url to users facebook page
        let appURL = NSURL(string: String(format: "fb://profile=%@", contact))!

        // build url to user page on facebook web site
        let webURL = NSURL(string: String(format: "http://www.facebook.com/%@", contact))!

        openURL(appURL, webURL: webURL)
    }
}

我认为这将是一种更清洁的方式来进行nil 检查,而不是稍后强制解包值。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-07-09
    • 2019-06-01
    • 2019-11-29
    • 2017-12-20
    • 2019-08-06
    • 2021-02-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多