字段已确认值但仍然出现解包错误?
field has value confirmed but still get unwrap error?
此代码块在尝试设置 appURL 时失败,即使 if 测试成功并且托管对象联系人将所有字段设置为非 nil 值并且某些 contact.facebook 有一个值所以我不能明白为什么我在尝试解包时找不到 nil 了吗?
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)
}
}
我建议用更好的方式来做,比如:
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
检查,而不是稍后强制展开值。
此代码块在尝试设置 appURL 时失败,即使 if 测试成功并且托管对象联系人将所有字段设置为非 nil 值并且某些 contact.facebook 有一个值所以我不能明白为什么我在尝试解包时找不到 nil 了吗?
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)
}
}
我建议用更好的方式来做,比如:
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
检查,而不是稍后强制展开值。