我試試看了解SWIFT 2.這裏新的錯誤處理的事情是我做的:我首先聲明一個錯誤枚舉:斯威夫特DO-的try-catch語法
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可以理解當每個case處理時它都是詳盡無遺的。
你做不指定你拋出的錯誤類型,所以Swift無法確定所有可能的選項 –
有沒有辦法指定錯誤的類型? – mustafa
我在新版本的Swift書中找不到任何東西 - 現在只有關鍵字 –