Start learning free

LESSON 69 OF 71 · PROJECTS: OBJECT-ORIENTED

Vending Machine in Swift: A Class with State

Practice Read the full explanation

Build a VendingMachine class for a machine that sells one kind of item for a fixed price. It keeps the money inserted so far (the credit), sells an item when the credit is enough, and gives the remaining credit back on request. A new object is made with VendingMachine().

Rules:

  • State. A new machine has credit 0 and price 150 (every item costs 150). Declare private var credit = 0.0 and private let price = 150.0.
  • func insert(_ amount: Double) adds amount to the credit. Nothing is printed or returned.
  • func select() -> String tries to buy one item and returns a string:
    • If the credit is less than the price, return "Need N more", where N is the missing amount (price - credit) as a whole number, for example "Need 100 more". The credit does not change.
    • Otherwise (the credit is equal to or greater than the price, so exact payment works), subtract the price from the credit and return "Dispensing!". Any extra money stays in the credit.
  • func refund() -> Double returns the whole credit and sets it back to 0, so asking again right away returns 0.

You start with this driver below your code:

class Solution {
    func mainFunction() {
        let machine = VendingMachine()
        machine.insert(50.0)
        print(machine.select())
        machine.insert(150.0)
        print(machine.select())
        print("Refunded: \(Int(machine.refund()))")
        machine.insert(150.0)
        print(machine.select())
        print("Refunded: \(Int(machine.refund()))")
        machine.insert(100.0)
        print(machine.select())
        print("Refunded: \(Int(machine.refund()))")
    }
}

Walk through it: 50 is not enough, so you see Need 100 more. After 150 more the credit is 200, so the machine dispenses and keeps 50 (200 - 150), and the refund is 50. Then 150 is exact payment: it dispenses and the refund is 0. Finally 100 is short by 50, the credit stays 100, and the refund is 100.

Expected output:

Need 100 more
Dispensing!
Refunded: 50
Dispensing!
Refunded: 0
Need 50 more
Refunded: 100

Convert the missing amount with Int(price - credit) and put it into the text with string interpolation: "Need \(Int(price - credit)) more". Do the subtraction only when the item is dispensed, not when the credit is too low. If you forget it, the leftover credit is wrong and the refund is too big.

In the refund method, save the credit first, then reset it to 0, then return what you saved. Return the saved constant, not credit.

class VendingMachine {
    private var credit = 0.0
    private let price = 150.0

    func insert(_ amount: Double) {
        credit += amount
    }

    func select() -> String {
        if credit < price { return "Need \(Int(price - credit)) more" }
        credit -= price
        return "Dispensing!"
    }

    func refund() -> Double {
        let amount = credit
        credit = 0.0
        return amount
    }
}

STEP 1 OF 13
    Ctrl + Enter to check

    SWIFT · PROJECTS: OBJECT-ORIENTED

    Vending Machine in Swift, explained

    Problem overview

    The lesson asks for a VendingMachine class that sells one kind of item for a fixed price. It remembers the money inserted so far, called the credit, sells an item when the credit is enough, and returns the leftover credit on request. A new machine comes from VendingMachine() and starts with credit 0. Its price is 150, declared as private var credit = 0.0 and private let price = 150.0.

    • insert(_ amount: Double) adds the amount to the credit and prints and returns nothing.
    • select() -> String tries to buy one item. If the credit is below the price, it returns "Need N more" with N as the missing whole number and leaves the credit alone. Otherwise it subtracts the price and returns "Dispensing!". Paying exactly 150 works, and extra money stays in the credit.
    • refund() -> Double returns the whole credit and sets it back to 0.

    The driver inserts 50 and selects, which is short. It inserts 150 more for a credit of 200, so the machine dispenses and keeps 50. The refund is 50. Then it pays exactly 150, which dispenses with a refund of 0. Last, 100 is 50 short, the credit stays at 100, and the refund is 100:

    Need 100 more
    Dispensing!
    Refunded: 50
    Dispensing!
    Refunded: 0
    Need 50 more
    Refunded: 100
    

    Approach: state plus guarded actions

    This is a small state machine in the plainest form: one number, the credit, and three methods that read or change it. The rule to keep straight is that each method changes the credit only when it should.

    • insert always changes it, by adding.
    • select changes it only on a successful sale. A failed attempt just reports what is missing.
    • refund always resets it to zero.

    Because the price is a let, it can't change after the machine is built, and because both properties are private, outside code can't edit the credit directly.

    Step by step

    1. Declare the class and write its closing brace at once. Each machine made from it keeps its own credit.
    2. Add private var credit = 0.0. Writing 0.0 makes Swift infer a Double, and a new machine holds no money.
    3. Add private let price = 150.0. It is set once and never changes.
    4. Start insert, with the parameter written as _ amount so callers need no label.
    5. Add the amount to the credit with credit += amount, so earlier money isn't replaced.
    6. Start select, with no parameters and a String result.
    7. Handle too little money: if credit < price, return the text with the missing amount, Int(price - credit), put inside the string with interpolation. This early return leaves the credit unchanged.
    8. Subtract the price from the credit. Only a paid-for item reaches this line.
    9. Return "Dispensing!".
    10. Start refund, returning a Double.
    11. Save the credit in a constant amount. Once the credit is reset, its old value is gone, so it must be saved first.
    12. Reset credit to 0.0.
    13. Return amount, the money to give back.

    The solution in Swift

    class VendingMachine {
        private var credit = 0.0
        private let price = 150.0
    
        func insert(_ amount: Double) {
            credit += amount
        }
    
        func select() -> String {
            if credit < price { return "Need \(Int(price - credit)) more" }
            credit -= price
            return "Dispensing!"
        }
    
        func refund() -> Double {
            let amount = credit
            credit = 0.0
            return amount
        }
    }
    
    class Solution {
        func mainFunction() {
            let machine = VendingMachine()
            machine.insert(50.0)
            print(machine.select())
            machine.insert(150.0)
            print(machine.select())
            print("Refunded: \(Int(machine.refund()))")
            machine.insert(150.0)
            print(machine.select())
            print("Refunded: \(Int(machine.refund()))")
            machine.insert(100.0)
            print(machine.select())
            print("Refunded: \(Int(machine.refund()))")
        }
    }
    

    Details worth knowing

    • Inferred types. 0.0 and 150.0 are Double literals, so no annotation is needed. If you wrote private var credit = 0, it would be an Int, and credit += amount with a Double wouldn't compile.
    • Int(price - credit) converts the missing amount to a whole number so the message has no decimals. It truncates toward zero. With a credit of 149.5, select() returns Need 0 more, although the item is still not sold.
    • String interpolation. "Need \(Int(price - credit)) more" evaluates the expression inside \( ) and inserts the result. Without the Int conversion, Swift would insert the Double as is, and the text would read Need 100.0 more.
    • Methods that change state don't need mutating, because this is a class. A struct would need that keyword.
    • The early return in select replaces an else. Any code below the if runs only when the credit is enough.

    Edge cases and common mistakes

    • Subtracting the price on a failed sale. If the subtraction came before the check, a short credit would go negative and the refund would be wrong.
    • Forgetting to subtract on success. The customer would keep the full credit, and the refund would be too large. With the driver's first purchase, the refund would be 200 instead of 50.
    • Using <= instead of <. That rejects exact payment. A credit of exactly 150 must dispense.
    • Returning credit after resetting it. In refund, credit = 0.0; return credit always returns 0. Return the saved amount.
    • Replacing instead of adding. credit = amount in insert loses money that was inserted earlier.
    • Refunding twice. A second refund() right after the first returns 0.0, because the credit was reset.

    Testing

    With a credit of 400, three selects in a row each take 150 until the credit runs out:

    let m3 = VendingMachine()
    m3.insert(400)
    print(m3.select(), m3.select(), m3.select(), m3.refund())
    
    Dispensing! Dispensing! Need 50 more 100.0
    

    Two sales use 300, the third attempt is 50 short, and the 100 left over comes back as a refund. Also try insert(149.5) followed by select(), which gives Need 0 more.

    Keep going with Swift1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free