0

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.)

alexhuang91
  • 91
  • 1
  • 9
  • "99%" duplicate of http://stackoverflow.com/questions/25708649/downcasting-optionals-in-swift-as-type-or-as-type. – Martin R Aug 19 '15 at 17:09
  • not really, the topic does not mention the bridge (`as`) operator – vadian Aug 19 '15 at 17:19
  • Not a duplicate. I understand the usage of `as` vs `as?` vs `as!`. I'm asking if `as? NSString` === `as NSString? as? NSString` and why iOS 8.4 broke `as? NSString` returns nil that while dealing with CFString classes. – alexhuang91 Aug 21 '15 at 20:29

1 Answers1

1

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
vadian
  • 274,689
  • 30
  • 353
  • 361
  • 1
    `as NSString?` *is* supported, e.g. if applied to a `CFString?`. – Martin R Aug 19 '15 at 17:29
  • Do you have a source? I couldn't find it in the Language Guide. if `as` is followed by a type, the marks are always right after `as` – vadian Aug 19 '15 at 17:35
  • `NSString?` *is* a type, it is `Optional`. – Martin R Aug 19 '15 at 17:36
  • Might be but I've never seen `as ?` (`as` without and `` with a mark) in Swift code provided by Apple – vadian Aug 19 '15 at 17:40
  • Can Unmanaged! ever return nil? (It seems unclear since it's an unmanaged class, and hence why I'm utilizing either an optional class or an optional cast) – alexhuang91 Aug 21 '15 at 20:22
  • Additionally, `as NSString?` is supported syntax because you are intentionally casting it to be an optional class. The cast operation itself is orthogonal to the class it is being cast to. – alexhuang91 Aug 21 '15 at 20:26