Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why would Error always be NSError?

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?

like image 762
Matias Avatar asked Nov 30 '16 21:11

Matias


People also ask

How do you convert error to NSError?

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.

What is NSError in Swift?

Information about an error condition including a domain, a domain-specific error code, and application-specific information.


1 Answers

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

like image 175
russbishop Avatar answered Sep 27 '22 02:09

russbishop