Multi-pattern catch clauses
In the previous section, we had code that looked like this:
do {
try myTeam.addPlayer(player:("David", "Ortiz", 34))
} catch PlayerNumberError.NumberTooHigh(let description) {
print("Error: \(description)")
} catch PlayerNumberError.NumberTooLow(let description) {
print("Error: \(description)")
} catch PlayerNumberError.NumberAlreadyAssigned {
print("Error: Number already assigned")
} catch {
print("Error: Unknown Error")
}
You will notice that the catch
clause for the PlayerNmberError.NumberTooHigh
and PlayerNumberError.NumberTooLow
errors contains duplicate code. When you are developing, it is always good to find a way to eliminate duplicate code like this. However, prior to Swift 5.3, we did not have a choice. Swift introduced multi-pattern catch
clauses with SE-0276 in Swift 5.3 to help reduce duplicate code like this. Let's take a look at this by rewriting...