Why and how any ErrorType can always be casted to NSError?

I installed Xcode 7 GM (7A218) today, and I got an interesting warning.


Dialogue.swift:91:25: Conditional cast from 'T' to 'NSError' always succeeds


Here's my source code.


  static func runErrorAlertModally<T: ErrorType>(error: T) {
       func makeAlert() -> NSAlert {
            if let error = error as? NSError { // Conditional cast from 'T' to 'NSError' always succeeds
                 return NSAlert(error: error)
            }
            else {
                 let a = NSAlert()
                 a.messageText = "\(error)"
                 return a
            }
       }
       makeAlert().runModal()
  }


AFAIK, ErrorType is just a marker type to mark a type can be thrown. But "why" and "how" `ErrorType` can be casted into `NSError` without any special treatment?

Because ErrorType has NSError as implicit Superclass.

That's incorrect, ErrorType is a protocol. The reason this works is because of "compiler magic." The compiler automatically emits the code necessary to translate between any ErrorType and NSError.

Ah my NSError 😉 - I assumed the compilermagic was a implicit superclass in the background.

Probably he only said with compiler does not use a class to do this and the ErrorType requirements match exactly as NSError so is "Toll free bridged".


But magic is more fun.