Swift - Checking unmanaged address book single value property for nil

前端 未结 3 889
暗喜
暗喜 2020-12-03 21:42

I\'m relative new to iOS-Development and swift. But up to this point I was always able to help myself by some research on stackoverflow and several documentations and tutori

3条回答
  •  长情又很酷
    2020-12-03 22:23

    If I want the values associated with various properties, I use the following syntax:

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

    Or you can use optional binding:

    if let first = ABRecordCopyValue(person, kABPersonFirstNameProperty)?.takeRetainedValue() as? String {
        // use `first` here
    }
    if let last  = ABRecordCopyValue(person, kABPersonLastNameProperty)?.takeRetainedValue() as? String {
        // use `last` here
    }
    

    If you really want to return a non-optional, where missing value is a zero length string, you can use the ?? operator:

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

提交回复
热议问题