Multi-pattern catch clauses
About 2 min
Multi-pattern catch clauses 관련
HACKING WITH SWIFT
What's new in Swift?
Multi-pattern catch clauses | Changes in Swift 5.3
Multi-pattern catch clauses
Available from Swift 5.3
SE-0276 (apple/swift-evolution
) 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.
Other Changes in Swift 5.3
Multiple trailing closures | Changes in Swift 5.3
Multiple trailing closures
Synthesized Comparable conformance for enums | Changes in Swift 5.3
Synthesized Comparable conformance for enums
self is no longer required in many places | Changes in Swift 5.3
self is no longer required in many places
Type-based program entry points | Changes in Swift 5.3
Type-based program entry points
where clauses on contextually generic declarations | Changes in Swift 5.3
where clauses on contextually generic declarations
Enum cases as protocol witnesses | Changes in Swift 5.3
Enum cases as protocol witnesses
Refined didSet semantics | Changes in Swift 5.3
Refined didSet semantics
A new Float16 type | Changes in Swift 5.3
A new Float16 type
Swift Package Manager gains binary dependencies, resources, and more | Changes in Swift 5.3
Swift Package Manager gains binary dependencies, resources, and more