// 定义错误,用来表示数组访问错误
enum ShoppingError:Error{
caseGoodsNotExist(String)
caseGoodsNotEnough(String)
casepayNotEnough(String)
}
classShopping {
vargoodsList = ["可口可乐":(price:3.0,number:100),
"百事薯片":(price:8.0,number:200),
"士力架":(price:6.0,number:300),
"阿尔卑斯":(price:3.0,number:200),
"肉粒多":(price:28.0,number:700),
]
funcbuyGoods(name:String,num:Int,pay:Double)throws->Void{
guardletgoods =goodsList[name]else{
throwShoppingError.GoodsNotExist("商品不存在")
}
guardgoods.number >= numelse{
throwShoppingError.GoodsNotEnough("库存不足")
}
guardpay >= (goods.price *Double(num)) else{
throwShoppingError.payNotEnough("金额不足")
}
letleftMemoey = pay - goods.price *Double(num)
// 打印清单
print("\(name) \(goods.price) \(num) \(leftMemoey)")
}
}
var s = Shopping()
do{
trys.buyGoods(name:"可口可乐", num:10, pay:1)
}catchShoppingError.GoodsNotExist{
print("商品不存在")
}catchShoppingError.GoodsNotEnough{
print("库存不足")
}catchShoppingError.payNotEnough{
print("金融不足")
}
网友评论