我正在使用我的应用中的联系人,用户可以选择联系人姓名... 但如果名字或姓氏为空,我会得到这个常见错误:
致命错误:在解包可选值时意外发现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
}
答案 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)")
}