Swift 类型不符合协议(protocol)

标签 swift protocols

<分区>

错误发生在类 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
    }
}

感谢任何指向正确方向的帮助或指示。

最佳答案

我将您的代码复制到 IBM Sandbox 中,由于您没有粘贴所有代码,因此不得不进行一些简化。尽管如此,我还是遇到了同样的第一个错误。第二个错误是解释问题的原因:

protocol requires property 'amountDeposited' with type 'Double'

您在类定义中拼错了属性。

关于Swift 类型不符合协议(protocol),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39359425/

相关文章:

ios - 通过扩展向协议(protocol)添加功能的原因是什么,为什么不把它放在协议(protocol)本身的定义中呢?

ios - 一般问题,有什么建议吗?

Swift 单按钮处理音频录制、暂停和恢复

ios - "Missing argument parameter ' 队列 ' in call"

ios - 导入协议(protocol)时没有类型或协议(protocol)错误

objective-c - objective-c - 获取协议(protocol)的父级列表

ios - 日期选择器看起来像文本字段的输入一样被压扁

swift - 暂停和恢复 SpriteKit 游戏

ios - 具有多个 View 的 ScrollView iOS Autolayout

swift - 属性 'self.myDelegate' 未在 super.init 中初始化 - 委托(delegate)