#SwiftLang Challenge: Oddball Casting

Answer: Conform to ErrorType and cast to NSError.

Any Swift type – enumeration, class, or structure – supports ErrorType by declaring protocol conformance. Internally, an ErrorType implements two key NSError features – the string domain (_domain) and the numeric code (_code).

These features provide compatibility with NSError and enable you to cast any conforming type, regardless of whether it is a class, enumeration, or structure to NSError.

Casting produces a minimal NSError instance populated with the code and domain. The resulting error discards all custom state you have added.

struct MyError: ErrorType {}
print(ErrorStruct() as NSError)   
    // Error Domain=ErrorStruct Code=1 "(null)"

I’d love to populate the localized error description in casting to eliminate that “(null)” bit but I honestly cannot figure that part out other than manually constructing a secondary NSError through a computed property. (If you know how to cast with an intact description, do please let me know.)

Update:

One Comment

  • Should ErrorStruct() be MyError()?