0

I'm working with contacts in my app, user can choose a contact name… but if first name or last name being empty, I will get this common error:

fatal error: unexpectedly found nil while unwrapping an Optional value

I know my question maybe duplicate, but I have read some articles but I couldn't find out how to solve mine.

Here is my code:

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


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

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

I want to fill textfield anyway.

EDIT:

I have found this solution from related question:

 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
}
Jerry Stratton
  • 3,287
  • 1
  • 22
  • 30
zzmasoud
  • 164
  • 1
  • 8

2 Answers2

1

Sprinkle some ?'s around to account for the nil, e.g.,

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

You should also be prepared for the possibility than firstName may be nil, and, e.g., use optional binding with if let firstName: ABMultiValueRef = …, and put any code relying on firstName in the then-branch of the if. The whole thing would look something like:

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?
}
Arkku
  • 41,011
  • 10
  • 62
  • 84
0

Try this,

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

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

}
Manikandan D
  • 1,422
  • 1
  • 13
  • 25