Swift 2 CFType Conversion

In Swift 1.2 I had a C function with the following signature:

__nonnull CFArrayRef FDCreateSupportedAudioFileExtensions() CF_RETURNS_RETAINED;

I know that this function returns an array of

CFStringRef
instances, so I called it from Swift like this:
let supportedAudioTypes = FDCreateSupportedAudioFileExtensions() as! [String]

and everything worked as expected. However, in Swift 2 this code fails at runtime due to the forced cast (

EXC_BAD_INSTRUCTION
). I'm able to get things working with the following:
let supportedAudioTypes = FDCreateSupportedAudioFileExtensions() as NSArray as! [String]

I'm unsure what changed from Swift 1.2 to 2.0. Is this a bug in the current version of Swift or have I missed something? Everything I've read implies that CFTypes are toll-free bridged to their Swift counterparts so I'm not sure why what used to work is now failing.

I agree that it doesn't make sense for the first not to work but the second to work. If you haven't already, please file a bug report with your project attached.


One possibility is that in your first example you never actually imported Foundation. If you only use Core Foundation, Swift doesn't set up all of the same bridging infrastructure that it would otherwise.

Thanks for the response. I filed bug 22593670 which includes a project recreating the problem. To answer your question about importing Foundation vs. CoreFoundation- I imported CoreFoundation only in my C wrapper. Importing Foundation from Swift didn't help the issue.

Same issue here causing many headaches and this breaks code that used optional binding: if let x = functionThatReturnsCFType() as? String {} now always fails Breaks code all over, silently!

Would be nice if someone from Apple could take a look at this as this looks to be a serious issue in Swift 2.0. CFType conversions, especially when used with optional return values are *extremely* broken.

Here's a simple example:


        let utis = UTTypeCreateAllIdentifiersForTag(kUTTagClassFilenameExtension, "mov", nil)?.takeRetainedValue()

How do we get a [String] out of this?? Nothing seems to work...

You'd better read the original post carefully.

let utis = UTTypeCreateAllIdentifiersForTag(kUTTagClassFilenameExtension, "mov", nil)?.takeRetainedValue() as NSArray? as! [String]
print(utis[0]) //->com.apple.quicktime-movie
Swift 2 CFType Conversion
 
 
Q