alexhuang91
alexhuang91

Reputation: 91

Swift casting statement with CF -> NS classes

While trying to integrate the Address Book framework and converting CF types to NS Classes to Swift classes, I noticed something strange:

ABRecordCopyCompositeName(record)?.takeRetainedValue() as? NSString

returns nil

ABRecordCopyCompositeName(record)?.takeRetainedValue() as NSString?

returns Optional("John Smith")

My question is that isn't as? NSString synonymous to as NSString? as? NSString? (If so, why not?)

Therefore, ABRecordCopyCompositeName(record)?.takeRetainedValue() as? NSString should be equivalent to ABRecordCopyCompositeName(record)?.takeRetainedValue() as NSString? as? NSString which should return "John Smith".

(This was working on iOS 8.3, but iOS 8.4 broke my AddressBook feature.)

Upvotes: 0

Views: 267

Answers (1)

vadian
vadian

Reputation: 285190

as (NS)String? is no supported syntax, even it might work in some way.
Either you can cast forced (as!) or optional (as?) or you can bridge (as) and there's no exclamation/question mark after the type.

ABAddressBookCopyArrayOfAllPeople() returns Unmanaged<CFArray>! and ABRecordCopyCompositeName() returns Unmanaged<CFString>!, both types are unwrapped optionals, so after calling takeRetainedValue() you can bridge to NSString

ABRecordCopyCompositeName(record).takeRetainedValue() as NSString

or further to String

ABRecordCopyCompositeName(record).takeRetainedValue() as NSString as String

Upvotes: 1

Related Questions