點擊查看源碼git
//錯誤處理 func test() { //錯誤枚舉 需ErrorType協議 enum ErrorEnum: Error { case `default` //普通錯誤 case other(tag: Int) //高級錯誤 可攜帶數據 } class SomeClass { func canThrowErrors(_ str: String) throws { //當str不爲Default時 輸出錯誤 guard str == "Default" else { throw ErrorEnum.default } //當str不爲Other時輸出錯誤 guard str == "Other" else { throw ErrorEnum.other(tag: 5) } } } let sClass = SomeClass() //try! sClass.canThrowErrors("Default") // 強制調用 錯誤時程序閃退。 do { try sClass.canThrowErrors("Default") try sClass.canThrowErrors("Other") } catch ErrorEnum.default { print("默認錯誤") } catch ErrorEnum.other(let tag) where tag == 5 { print("錯誤代碼:\(tag)") } catch ErrorEnum.other(let tag) { print("其餘錯誤:\(tag)") } catch { // 在捕獲中 隱式攜帶error錯誤。 print("未知錯誤:\(error)") } /* print 錯誤代碼:5 */ }