//: playground - noun: a place where people can play
import uikit
// 下面的三個用於除錯,在真機上不起作用
assert(1>0) // 必須滿足括號裡面的邏輯,不然停止
assert(1>0, "error") // 必須滿足括號裡面的邏輯,不然停止並報錯
assertionfailure("error!") // 直接停止並報錯
// 下面的三個和assert作用一模一樣,在真機上也起作用
precondition(1>0)
precondition(1>0, "error")
fatalerror("error")
import uikit
// 自動販賣機
class vendingmachine
let type: itemtype
let price: int
var count: int
}// 繼承乙個錯誤處理的類,名字叫error
enum itemerror: error
private var items = ["mineral water" : item(type: .water, price:2, count:10),
"coca cola" : item(type: .cola, price: 3, count: 5),
"orange juice" : item(type: .juice, price: 5, count: 3)]
func vend(itemname: string, money: int, count: int) throws -> int
guard money >= item.price else
guard item.count > 0 else
guard count > 0 else
dispenseitem(itemname: itemname)
return money - item.price * item.count
}private func dispenseitem(itemname: string)
}
func vend(itemname itemname: string, money: int) throws -> int
guard money >= item.price else
guard item.count > 0 else
dispenseitem(itemname: itemname)
return money - item.price
}
enum itemerror: error, customstringconvertible
}}
pocketmoney = try! machine.vend(itemname: "coca cola", money: pocketmoney)
try? machine.vend(itemname: "coca cola", money: pocketmoney)
do
catch vendingmachine.itemerror.nosuchitem
catch vendingmachine.itemerror.notenoughmoney(let price)
catch vendingmachine.itemerror.outofstock
catch
do
catch let error as vendingmachine.itemerror
catch
func vend(itemname itemname: string, money: int) throws -> int
guard let item = items[itemname] else
guard money >= item.price else
guard item.count > 0 else
defer
dispenseitem(itemname: itemname)
return money - item.price
}
Swift 錯誤處理
宣告列舉錯誤型別 enum printererror error 捕捉異常的五種方式 1.使用throw 來丟擲乙個錯誤 func send job int,printername string throws string return job sent 2.do catch 在 塊中執行操作,do...
Swift 錯誤處理
override func viewdidload 丟擲錯誤 throw vendingmachineerror.insufficientfunds coinsneeded 5 2.處理錯誤 swift 中有四種方式處理錯誤 1.將錯誤從乙個函式傳播 propagate 到呼叫它的 2.用 do c...
swift 中錯誤處理
enum customerror error 定義乙個測試用的類 class testerrorclass name s func showstring 第一種使用方式,執行 後,直接丟擲異常,中止執行 let tes trytesterrorclass s 執行結果 lldb expr 123.c...