GO FURTHER, FASTER: Try the Swift Career Accelerator today! >>

Multi-pattern catch clauses

Available from Swift 5.3

Paul Hudson      @twostraws

SE-0276 introduced the ability to catch multiple error cases inside a single catch block, which allows us to remove some duplication in our error handling.

For example, we might have some code that defines two enum cases for an error:

enum TemperatureError: Error {
    case tooCold, tooHot
}

When reading the temperature of something, we can either throw one of those errors, or send back “OK”:

func getReactorTemperature() -> Int {
    90
}

func checkReactorOperational() throws -> String {
    let temp = getReactorTemperature()

    if temp < 10 {
        throw TemperatureError.tooCold
    } else if temp > 90 {
        throw TemperatureError.tooHot
    } else {
        return "OK"
    }
}

When it comes to catching errors thrown there, SE-0276 lets us handle both tooHot and tooCold in the same way by separating them with a comma:

do {
    let result = try checkReactorOperational()
    print("Result: \(result)")
} catch TemperatureError.tooHot, TemperatureError.tooCold {
    print("Shut down the reactor!")
} catch {
    print("An unknown error occurred.")
}

You can handle as many error cases as you want, and you can even bind values from your errors if needed.

Hacking with Swift is sponsored by Essential Developer.

SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until February 9th.

Click to save your free spot now

Sponsor Hacking with Swift and reach the world's largest Swift community!

Other changes in Swift 5.3…

Download all Swift 5.3 changes as a playground Link to Swift 5.3 changes

Browse changes in all Swift versions

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.