【发布时间】:2015-08-23 14:09:03
【问题描述】:
我尝试理解 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 可以理解在处理每个案例时它是详尽的。
【问题讨论】:
-
你没有指定你抛出的错误类型,所以 Swift 无法确定所有可能的选项
-
有没有办法指定错误的类型?
-
我在新版 Swift 书籍中找不到任何内容 - 现在只有 throws 关键字
-
在操场上为我工作,没有错误或警告。
-
Playgrounds 似乎允许
do块在顶层是非穷尽的 - 如果你将 do 包装在一个非抛出函数中,它将产生错误。