Not only the compiler requires a default case for both switch and catch but it imposes this default case to be the last case. For switch, if a case: occurs after default:, the compiler raises an error whereas for catch it only raises a warning telling that the next catch will be never executed.
The following code works but the case “division by 1” is never executed.
enum Error: Swift.Error {
case divisionBy0
case divisionBy1
}
func div(num: Int, den: Int) throws-> Double {
guard den != 0 else {
throw Error.divisionBy0
}
guard den != 1 else {
throw Error.divisionBy1
}
return Double(num/den)
}
do {
let x = try div(num:16, den:1)
print("Result: \(x)")
} catch Error.divisionBy0 {
print("Division by 0")
} catch {
print("General error")
} catch Error.divisionBy1 {
print("Division by 1 is useless")
}