出乎意料地发现零

时间:2015-07-14 20:01:59

标签: xcode swift null optional

我正在使用我的应用中的联系人,用户可以选择联系人姓名... 但如果名字或姓氏为空,我会得到这个常见错误:

  

致命错误:在解包可选值时意外发现nil

我知道我的问题可能重复,但我读了一些文章,但我找不到如何解决我的问题。

这是我的代码:

let firstName: ABMultiValueRef? =
        ABRecordCopyValue(person,
            kABPersonFirstNameProperty).takeRetainedValue() as ABMultiValueRef


        let lastName: ABMultiValueRef? =
        ABRecordCopyValue(person,
            kABPersonLastNameProperty).takeRetainedValue() as ABMultiValueRef

        titleField.text = ("\(firstName) \(lastName)")

无论如何我想填写文本字段。

修改

我从相关问题找到了这个解决方案:

 var name:String = ""
        if let first = ABRecordCopyValue(person, kABPersonFirstNameProperty)?.takeRetainedValue() as? String {
            name += first
        }
        if let last  = ABRecordCopyValue(person, kABPersonLastNameProperty)?.takeRetainedValue() as? String {
            name += last
        }
        titleField.text =  name
}

2 个答案:

答案 0 :(得分:1)

?上点上一些nil,例如,

let firstName: ABMultiValueRef? =
        ABRecordCopyValue(person,
            kABPersonFirstNameProperty)?.takeRetainedValue() as? ABMultiValueRef

您还应该为firstName可能nil之间的可能性做好准备,例如,使用if let firstName: ABMultiValueRef = …的可选绑定,并根据firstName放置任何代码在if的then分支中。整个事情看起来像是:

if let firstName: ABMultiValueRef = ABRecordCopyValue(person,
        kABPersonFirstNameProperty)?.takeRetainedValue() as? ABMultiValueRef,
       lastName: ABMultiValueRef = ABRecordCopyValue(person,
        kABPersonLastNameProperty)?.takeRetainedValue() as? ABMultiValueRef {
    titleField.text = "\(firstName) \(lastName)"
} else {
    titleField.text = "" // <- handle the failure case?
}

答案 1 :(得分:0)

试试这个,

if((let first = ABRecordCopyValue(person, kABPersonFirstNameProperty)?.takeRetainedValue() as? String) && (let last  = ABRecordCopyValue(person, kABPersonLastNameProperty)?.takeRetainedValue() as? String)) {

    titleField.text = ("\(firstName) \(lastName)")

}