enum ErrorType:Error{
case invalidProduct
case insuffficientCoisn(coinsNeeded:Int)
case outOfStock


}
struct Product {
var price:Int
var count:Int
}
var totalCoins=20
class Shop{
var products=[
"pudding":Product(price: 12, count: 7),
"Donut":Product(price: 10, count: 4),
"Cheesepuff":Product(price: 7, count: 13)
]
func sell(ProductName:String) throws{
guard let product=products[ProductName] else {
throw ErrorType.invalidProduct
}
guard product.count>0 else {
throw ErrorType.outOfStock
}
guard product.price<=totalCoins else {
throw ErrorType.insuffficientCoisn(coinsNeeded: product.price-totalCoins)
}
totalCoins-=product.price
var newItem=product
newItem.count-=1
products[ProductName]=newItem
print(">>>>\(ProductName)")
}
}
var shop=Shop()
do{
//会抛出异常
// try shop.sell(ProductName: "Apple")
try shop.sell(ProductName: "pudding")
try shop.sell(ProductName: "pudding")
}
catch ErrorType.invalidProduct{
print("Invalid product.")
}catch ErrorType.outOfStock{
print("Out of stock.")
}catch ErrorType.insuffficientCoisn(coinsNeeded: let coinsNeeded){
print("Need an additional\(coinsNeeded) conin(s).")
}