我尝试理解 swift 2 中的新错误处理。这是我所做的:我首先声明了一个错误枚举:
enum SandwichError: ErrorType {
case NotMe
case DoItYourself
}
然后我声明了一个引发错误的方法(不是异常,这是一个错误。)。这是那个方法:
func makeMeSandwich(names: [String: String]) throws -> String {
guard let sandwich = names["sandwich"] else {
throw SandwichError.NotMe
}
return sandwich
}
问题出在调用方。下面是调用这个方法的代码:
let kitchen = ["sandwich": "ready", "breakfeast": "not ready"]
do {
let sandwich = try makeMeSandwich(kitchen)
print("i eat it \(sandwich)")
} catch SandwichError.NotMe {
print("Not me error")
} catch SandwichError.DoItYourself {
print("do it error")
}
do
在行编译器Errors thrown from here are not handled because the enclosing catch is not exhaustive
说. 但在我看来,它是详尽无遗的,因为SandwichError
枚举中只有两种情况。
对于常规的 switch 语句,swift 可以理解在处理每个案例时它是详尽的。