Uploaded image for project: 'Swift'
  1. Swift
  2. SR-14322

Bridging to NSError fails for instances of a class

    XMLWordPrintable

    Details

    • Type: Bug
    • Status: Open
    • Priority: Medium
    • Resolution: Unresolved
    • Component/s: Compiler
    • Labels:

      Description

      (Also posted in the Swift forum: Bridging to NSError fails for instances of a class.)

      According to SE-0112, every type that conforms to the Error protocol is implicitly bridged to NSError. This does not work with reference types, the last line in the following example does not compile:

      class MyError: Error {}
      
      extension MyError: CustomNSError {
          public static var errorDomain: String { "MyDomain" }
          public var errorCode: Int { 13 }
          public var errorUserInfo: [String : Any] { ["Foo" : "Bar" ] }
      }
      
      let sError = MyError()
      
      let nsError = sError as NSError
      // error: 'MyError' is not convertible to 'NSError'; did you mean to use 'as!' to force downcast?
      

      Inserting an “intermediate cast” to `Error` makes it compile and run as expected:

      let nsError = sError as Error as NSError
      print(nsError.userInfo)
      // ["Foo": "Bar"]
      

      That problem occurs only if the custom error type is a class, not with a struct or an enum.

        Attachments

          Activity

            People

            Assignee:
            Unassigned Unassigned
            Reporter:
            martin Martin
            Votes:
            1 Vote for this issue
            Watchers:
            3 Start watching this issue

              Dates

              Created:
              Updated: