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! While you're at it, check out some resources Treehouse students have shared here.

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

iOS Build a Vending Machine App in Swift 2.0 Displaying Additional Views Comparing Answers

Rodrigo Chousal
Rodrigo Chousal
16,009 Points

How does the "Insufficient Funds" error know the amount missing by just passing in let amount?

In this video, Pasan implements error-catching code, and one of his catch statements reads as follows:

 catch VendingMachineError.InsufficientFunds(let amount){
                showAlert("Insufficient Funds", message: "Additional $\(amount) needed to complete the transaction.")
            }

How does this parameter communicate with the app's model to extract the amount constant?

Reed Carson
Reed Carson
8,306 Points

has it actually been implemented yet? He often builds things ahead of time and plugs them in later. Did this code compile and work as expected?

JOSEPH LUNA
JOSEPH LUNA
13,625 Points

In the VendingMachine.swift File in the VendingMachine Class, we implemented this in the vend() function as the "throw" in the "else" block: else{ let amountRequired = totalPrice - amountDeposited //the math your looking for throw vendingMachineError.InsufficientFunds(required: amountRequired) } By declaring the local variable "let amount" in the parameter of the VendingMachineError.InsufficientFunds(required: amountRequired), the
"amount = "amountRequired" which returns the difference.

1 Answer

Andrea Miotto
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Andrea Miotto
iOS Development Techdegree Graduate 23,357 Points

In VendingMachine.swift

We have defined the case for InsufficientFunds exception

enum VendingMachineError: ErrorType {
    case InvalidSelection
    case OutOfStock
    case InsufficientFunds(required: Double)   //<<<< here we say that this case has an associate value
}

When we try to purchase we call the vend func, wich can throws error

func vend(selection: VendingSelection, quantity: Double) throws {
        //checking if the seleciotn is correct
        guard var item = inventory[selection] else {
            throw VendingMachineError.InvalidSelection
        }
        //checking if there are items left in the stock
        guard item.quantity > 0 else {
            throw VendingMachineError.OutOfStock
        }

        item.quantity -= quantity   //decreasing the quantity
        inventory.updateValue(item, forKey: selection)  //updating the item

        let totalPrice = item.price * quantity
        if amountDeposited >= totalPrice {
            amountDeposited -= totalPrice
        } else { //If we do not have enough money  (<<< THIS is the part you have to understand)
            let amountRequired = totalPrice - amountDeposited //we calculate how much we need
            throw VendingMachineError.InsufficientFunds(required: amountRequired) //than we throw the error with the associate value
        }
    }

In ViewController.swift

@IBAction func purchase() {
        if let currentSelection = currentSelection {
            do {
                try vendingMachine.vend(currentSelection, quantity: quantity)
                updateBalanceLabel()
            } catch VendingMachineError.OutOfStock {
                showAlert("Out of Stock")
            } catch VendingMachineError.InvalidSelection {
                showAlert("Invalid Selection")
            //we save the associate value in the amount constant, the associate value is calculated in the vend func
            } catch VendingMachineError.InsufficientFunds(required: let amount) { 
                showAlert("Insufficient Funds", message: "Additional $\(amount) needed to complete the transition")
            } catch let error {
                fatalError("\(error)")
            }

        } else {
            //FIXME: Alert user no selection
        }
    }

summarizing:

1- you try to buy

2- if you do not have enough money:

3- you calculate how much you are missing

4- throws an exception with the associated value of how much you're missing

5- display an alert, and in the message shows the associated value of how much you're missing.