<分区>
错误发生在类 VendingMachine: VendingMachineType{}
我似乎找不到导致问题的差异。我是不是漏掉了什么或者找错地方了?
如果我正确理解协议(protocol),它基本上确定了类要遵循的蓝图,据我所知,我找不到函数不遵循协议(protocol)设置的蓝图的地方。
协议(protocol):
protocol VendingMachineType {
var selection: [VendingSelection] { get }
var inventory: [VendingSelection: ItemType] { get set }
var amountDeposited: Double { get set }
init(inventory: [VendingSelection: ItemType])
func vend(selection: VendingSelection, quantity: Double) throws
func deposit(amount: Double)
func itemForCurrentSelection(selection: VendingSelection) -> ItemType?
}
类:
class VendingMachine: VendingMachineType {
let selection: [VendingSelection] = [.Soda, .DietSoda, .Chips, .Cookie, .Sandwich, .Wrap, .CandyBar, .PopTart, .Water, .FruitJuice, .SportsDrink, .Gum]
var inventory: [VendingSelection: ItemType]
var amountDesposited: Double = 10.0
required init(inventory: [VendingSelection : ItemType]) {
self.inventory = inventory
}
func vend(selection: VendingSelection, quantity: Double) throws {
guard var item = inventory[selection] else {
throw VendingMachineError.InvalidSelection
}
guard item.quantity > 0 else {
throw VendingMachineError.OutOfStock
}
//at this point we have an item and a quantity implement a cancel button as homework here.
//time to reduce quantity by amount purchased
item.quantity -= quantity
inventory.updateValue(item, forKey: selection)
//here we are checking to see if we have enough money and throwing an error if they do not
let totalPrice = item.price * quantity
if amountDesposited >= totalPrice {
amountDesposited -= totalPrice
} else {
let amountRequired = totalPrice - amountDesposited
throw VendingMachineError.InsufficientFunds(required: amountRequired)
}
}
func itemForCurrentSelection(selection: VendingSelection) -> ItemType? {
return inventory[selection]
}
func deposit(amount: Double) {
amountDesposited += amount
}
}
感谢任何指向正确方向的帮助或指示。