错误发生在班级VendingMachine: VendingMachineType{}
我似乎无法找到造成问题的差异。我错过了什么,还是我在错误的地方?
如果我正确理解协议,它基本上确定了要遵循的类的蓝图,据我所知,我无法找到该函数不遵循协议设置的蓝图的位置。
协议:
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
}
}
赞赏任何正确方向的帮助或指示。
答案 0 :(得分:3)
我将您的代码复制到IBM Sandbox中,因为您没有粘贴所有代码,所以必须进行一些简化。不过,我得到了同样的第一个错误。第二个错误是解释问题的原因:
protocol requires property 'amountDeposited' with type 'Double'
您在课程定义中错误拼写了该属性。
答案 1 :(得分:0)
您的VendingMachine
amountDeposited
是一个存储的属性。但协议只能声明计算属性。