If a contact's first name or last name is blank, will the value be nil
or ""
?
Asked
Active
Viewed 1,337 times
0

ma11hew28
- 121,420
- 116
- 450
- 651
2 Answers
2
The value will be nil
as of Xcode 6 Beta 4.
To see for yourself, run the following code twice:
// AppDelegate.swift
import AddressBookUI
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow!
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool {
var error: Unmanaged<CFError>?
let addressBookTemp = ABAddressBookCreateWithOptions(nil, &error)
if !addressBookTemp {
println(error)
return true
}
let addressBook = Unmanaged<NSObject>.fromOpaque(addressBookTemp.toOpaque()).takeRetainedValue()
ABAddressBookRequestAccessWithCompletion(addressBook, nil)
var allPeople: NSArray = ABAddressBookCopyArrayOfAllPeople(addressBook).takeRetainedValue()
println("allPeople.count: \(allPeople.count)")
for person in allPeople {
let firstNameTemp = ABRecordCopyValue(person, kABPersonFirstNameProperty)
let firstName: NSObject! = Unmanaged<NSObject>.fromOpaque(firstNameTemp.toOpaque()).takeRetainedValue()
if firstName {
println("firstName: \(firstName)")
} else {
println("fristName is nil")
}
let lastNameTemp = ABRecordCopyValue(person, kABPersonLastNameProperty)
let lastName: NSObject! = Unmanaged<NSObject>.fromOpaque(lastNameTemp.toOpaque()).takeRetainedValue()
if lastName {
println("lastName: \(lastName)")
} else {
println("lastName is nil")
}
}
return true
}
}

ma11hew28
- 121,420
- 116
- 450
- 651
2
If a person don't have first or last name the value will be nil
.
If you want to cast it to an empty string you can do this:
// Getting the first and the last name of person
let firstNameTemp = ABRecordCopyValue(person, kABPersonFirstNameProperty)?;
let firstName: NSObject? = Unmanaged<NSObject>.fromOpaque(firstNameTemp!.toOpaque()).takeRetainedValue();
var first_name = "";
if firstName != nil {
first_name = firstName! as NSString;
}
let lastNameTemp = ABRecordCopyValue(person, kABPersonLastNameProperty)?;
let lastName: NSObject? = Unmanaged<NSObject>.fromOpaque(lastNameTemp!.toOpaque()).takeRetainedValue();
var last_name = "";
if lastName != nil {
last_name = lastName! as NSString;
}

Hristo Atanasov
- 1,236
- 2
- 18
- 25
-
That is correct, and you would think there is some shorter Swift syntax for this. But firstNameTemp is not an Optional, even though it could be nil. But if anyone has a more concise way to do it, I'd love to see it. – Andrew Duncan Sep 01 '15 at 04:05