15. How to make the Error type compatible with NSError in Swift?

It will take about 2 minutes to finish reading this article.

To make the Error type compatible with NSError in Swift, you can conform your custom error type to the Error protocol and use the bridging of NSError. To ensure compatibility between Error and NSError, follow these steps:

  1. Have your custom error type conform to the Error protocol.

    1
    2
    3
    enum CustomError: Error {
    case someError
    }
  2. Use the bridging mechanism of NSError to bridge your Error type to NSError.

    1
    2
    let customError = CustomError.someError
    let nsError = customError as NSError
  3. Application

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    do {
    try doSomething()
    } catch {
    if let error = error as? CustomError {
    let userInfo = [NSLocalizedDescriptionKey: "Custom Error Occurred"]
    let nsError = NSError(domain: "com.example", code: 100, userInfo: userInfo)
    print(nsError)
    } else {
    // Handle other types of errors
    }
    }

By bridging your custom Error type to NSError, you can seamlessly handle errors between Swift and Objective-C, and utilize Swift’s error handling mechanism when interacting with Objective-C code. This compatibility ensures proper error handling in mixed programming scenarios.