/ 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.


Thanks for reading!

If you enjoyed this post, be sure to follow me on Twitter to keep up with the new content. There I write daily on iOS development, programming, and Swift.

Vadim Bulavin

Creator of Yet Another Swift Blog. Coding for fun since 2008, for food since 2012.

Follow