I have the following class defined on a Playground with Swift 3:
class MyError: Error {
}
Then, I create an instance of such class and check if it is a NSError
let firstError = MyError()
firstError is NSError // Output: false
The output is as expected, and I also get a warning which indicates Cast from 'MyError' to unrelated type 'NSError' always fails
. This makes total sense for me, but if I change the code a little bit and declare the variable as an Error
, I get a strange result:
var secondError: Error
secondError = MyError()
secondError is NSError // Output: true
And in this case I get a warning in the last line that says 'is' test is always true
. I don't get why an Error
would always be an NSError
, when the model is defined the other way round (NSError: Error
). Any idea what is going on here?
It should be possible to turn an arbitrary Swift enum that conforms to Error into an NSError by using the qualified type name as the domain key, the enumerator as the error code, and turning the payload into user data.
Information about an error condition including a domain, a domain-specific error code, and application-specific information.
This is intentional behavior to allow Swift Error
types to interop with Objective-C.
The compiler will only do the coercion when bridging Swift errors to Objective-C, or in your case where all you have is the Error
existential that could contain anything... remember it could just as well have come from a throws
function written in Objective-C. This also gives you an out to get the coercion if you need to pass an NSError
directly to some Objective-C method as a parameter (for whatever reason).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With