/ SWIFT

Error Pattern Matching in Swift

Swift errors can be pattern matched by their value. It’s useful when switching over an error. Any Error-conforming type is applicable, including the custom ones:

import Foundation
import CFNetwork

let error: Error = URLError(.badURL)

enum MyError: Error {
    case myError
}

switch error {
case URLError.badURL:
    print("Bad URL error found")
case CFNetworkErrors.cfErrorHTTPBadCredentials:
    break
case DecodingError.dataCorrupted:
    break
case MyError.myError:
    break
default:
    break
}

It will print:

Bad URL error found

Note how we are using different error types in a single switch statement. NSErrors can be used as well: they will be bridged automatically to Swift Errors.