Cast CFError to NSError in Swift

Hi,


I'm probably overlooking something obvious here. CFError is toll-free bridged with NSError, so I should just be able to do this*:

let myCFError: CFError? = nil
let myNSError: NSError? = myCFError

But this does not compile as "'CFError?' is not convertible to 'NSError?'"


Force casting thows a warning that "Cast from 'CFError? to 'NSError?' always fails":

let myCFError: CFError? = nil
let myNSError: NSError? = myCFError as! NSError?


What am I doing wrong here?


*) https://developer.apple.com/library/prerelease/ios/documentation/CoreFoundation/Reference/CFErrorRef/index.html

In Swift, you will always need to do an explict cast using 'as' for any bridged types, but the conversion is guaranteed to succeed.

(see OOPer's comment below)

I think the problem is that the toll-free bridging was supposed to happen between CoreFoundation and Foundation, so even though Swift supports bridging between CFError and NSError, it hasn't explicitly added support to convert CFError when it is wrapped in an Optional<CFError>.


As a workaround, you can use ?? (the nil coalescing operator) to unwrap the optional or return another value if the optional is nil (in this case, just nil again), so that the conversion is between the unwrapped CFError and NSError? or from nil to NSError?.

Accepted Answer

Maybe it's not a problem of optionality. In Swift 1.2 (Xcode Version 6.3.2 (6D2105)), this code causes error.

let myCFError: CFError = CFErrorCreate(nil, "", 0, nil)
let myNSError: NSError = myCFError as NSError //error: 'CFError' is not convertible to 'NSError'


And in Swift 2 (Xcode Version 7.0 beta (7A121l)), this code works as expected.

let myCFError: CFError? = nil
let myNSError: NSError? = myCFError as NSError?

Using "as NSError?" works now, so I must have had a typo in the playground I was testing this in (on Xcode 7 beta), because I'm sure I was getting an "[ ] is not convertible to [ ]" error when casting.


Maybe I accidentally left off the ? on "as NSError?" when I tried it?

Cast CFError to NSError in Swift
 
 
Q