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() -> Stringtries 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() -> Doublereturns 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.
insertalways changes it, by adding.selectchanges it only on a successful sale. A failed attempt just reports what is missing.refundalways 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
- Declare the class and write its closing brace at once. Each machine made from it keeps its own credit.
- Add
private var credit = 0.0. Writing0.0makes Swift infer aDouble, and a new machine holds no money. - Add
private let price = 150.0. It is set once and never changes. - Start
insert, with the parameter written as_ amountso callers need no label. - Add the amount to the credit with
credit += amount, so earlier money isn't replaced. - Start
select, with no parameters and aStringresult. - 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. - Subtract the price from the credit. Only a paid-for item reaches this line.
- Return
"Dispensing!". - Start
refund, returning aDouble. - Save the credit in a constant
amount. Once the credit is reset, its old value is gone, so it must be saved first. - Reset
creditto 0.0. - 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.0and150.0areDoubleliterals, so no annotation is needed. If you wroteprivate var credit = 0, it would be anInt, andcredit += amountwith aDoublewouldn'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()returnsNeed 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 theIntconversion, Swift would insert theDoubleas is, and the text would readNeed 100.0 more. - Methods that change state don't need
mutating, because this is a class. A struct would need that keyword. - The early
returninselectreplaces anelse. Any code below theifruns 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
creditafter resetting it. Inrefund,credit = 0.0; return creditalways returns 0. Return the savedamount. - Replacing instead of adding.
credit = amountininsertloses 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.
