Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community!

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial


What am I doing wrong here - Modelling the Vending Machine

In the modelling the Vending machine video, my code to decrease the inventory is not working. I can't figure it our for the life of me.

It would seem that it is something to do with the binary operator,

"Binary Operator '-=' cannot be applied to operands of type 'Double' and [VendingSelection: ItemType]'

My code is as follows,

struct VendingItem: ItemType {
    var price: Double
    var inventory: Double

class VendingMachine: VendingMachineType {

    let selection: [VendingSelection] = [.Soda, .DietSoda, .Chips, .Cookie, .Sandwich, .Wrap, .CandyBar, .PopTart, .Water, .FruitJuice, .SportsDrink, .Gum]

    var inventory: [VendingSelection: ItemType]

    var amountDeposited: 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.inventory > 0 else {
            throw VendingMachineError.OutOfStock


        item.inventory -= inventory

Worth noting. In the video Parsan has the struct with price and quantity. For some reason mine is price and inventory. Also, if it helps this is around the 8 minute mark on the video.

1 Answer

Ben Shockley
Ben Shockley
6,094 Points

From what I can tell, In your struct you've got your var as inventory, as well as inside your function, but the parameter that you are taking in your function for the number of items being purchased you have as quantity. I think this may be where your mistake is. If you renamed quantity to inventory I think you will be good to go. Right now it is trying to subtract the class variable inventory (which is a dictionary) from your inventory, instead of the function parameter that is passing in the amount to be purchased. Does this make sense, I feel like I am having trouble explaining it haha.

HA! Cheers Ben. I'll had a feeling it was something like that.

I will unpick my mistakes later and see how I get one.

Thanks for the reply.