我try 理解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
enum中只有两个病例.
对于常规的switch语句,Swift 可以理解,在处理每一个 case 时,它都是详尽的.