How do I get a value as a Swift type from an object of type Unmanaged<AnyObject>. My example is using an ABRecordRef
I'm creating a contact object to manage once I get the ABRecordRef, but I'm having trouble translating from ObjC. Here's what I have:
init(recordRef: ABRecordRef) {
if let firstName = ABRecordCopyValue(recordRef, kABPersonFirstNameProperty) {
self.firstName = firstName
}
}
If it were ObjC, I would do:
CFTypeRef firstNameRef = ABRecordCopyValue(recordRef, kABPersonFirstNameProperty);
if (firstNameRef) {
self.firstName = (__bridge NSString *)firstNameRef;
}
I can't seem to find the right combination of downcasting / conversion, so any help is appreciated.
Since NoOne answered before I solved it, I'll add the answer here:
If you look at the header of the
Unmanagedstruct type, you'll find this:So, because the
CFTypeRefis converted toUnmanaged<AnyObject>in Swift.Unmanageduses generics to define a return type, and it is declared like so:Our object is of type
Unmanaged<AnyObject>which means thattakeRetainedValue()will return typeT, or in our case, typeAnyObject. I use optional downcasting since my propertyfirstNameis of typeString?.You can use the
takeRetainedValuemethod to get your value out of yourUnmanagedobject. In Foundation API's, I'm guessing that they will mostly be of typeUnmanaged<AnyObject>!and a downcast will be required. The generic formula appears to be: