Problem overview
A shop keeps its orders in a cart, and the lesson asks for two classes that work together. A LineItem is one row of the cart: a product name, a price and a quantity. A Cart holds many rows and adds them up. The cart has line items rather than being one, which is called composition.
LineItem has constants name, price and quantity, an initializer init(_ name: String, _ price: Double, _ quantity: Int) and a method subtotal() -> Double that returns price times quantity. Cart keeps a private var items = [LineItem](), has add(_ item: LineItem) to append a row and total() -> Double to sum the subtotals.
The driver checks an empty cart, then an apple at price 5 and quantity 3, whose subtotal is 15. It adds the apple and bread (price 20, quantity 3) to a cart for a total of 75, then adds milk (price 10, quantity 2) for a total of 95:
Empty: 0
Subtotal: 15
Total: 75
Total: 95
Approach: each class does its own part
The design splits the work. A line item knows how to price itself: it has the price and the quantity, so it is the right place for subtotal(). The cart doesn't need to know how a subtotal is calculated. It asks each row for its own and adds the answers.
The cart never stores a running total. total() works the sum out each time it is called, from whatever rows are in the cart at that moment. That is why the driver's second Total line is larger than the first: the milk was added in between, and the next call to total() sees it. A stored total would have to be updated in every method that changes the cart, and a missed update would leave it wrong.
Step by step
- Declare
LineItemand write its closing brace right away. - Add
let name: String. It isletbecause a row's values never change once it is made. - Add
let price: Double. ADoubleholds decimals, in case a price isn't whole. - Add
let quantity: Int. The number bought is always whole. - Write the initializer. Each parameter gets an underscore before its name, so the driver can write
LineItem("Apple", 5.0, 3)without labels. - Store the name in
self.name. The parameter and the property share a name, soself.says which one is the property. - Store the price in
self.price. - Store the quantity in
self.quantity. Now a row remembers all three values. - Start
subtotal, returning aDouble. - Return
price * Double(quantity). Swift won't multiply aDoubleby anInt, so the quantity is converted first. - Declare
CartbelowLineItem. - Add the storage
private var items = [LineItem](). It isvarbecause the array grows as rows come in. - Start
add, taking aLineItemnameditemwith an underscore label. - Append the item to
items. The array keeps rows in the order they arrived. - Start
total, returning aDouble. - Create
var sum = 0.0. Starting at zero is what makes an empty cart total 0. - Loop with
for item in items. No index is needed, since the loop hands over each row. - Add the row's subtotal to
sum, by askingitem.subtotal(). - Return
sumafter the loop, so the line runs once, when every row has been added.
The solution in Swift
class LineItem {
let name: String
let price: Double
let quantity: Int
init(_ name: String, _ price: Double, _ quantity: Int) {
self.name = name
self.price = price
self.quantity = quantity
}
func subtotal() -> Double {
return price * Double(quantity)
}
}
class Cart {
private var items = [LineItem]()
func add(_ item: LineItem) {
items.append(item)
}
func total() -> Double {
var sum = 0.0
for item in items {
sum += item.subtotal()
}
return sum
}
}
class Solution {
func mainFunction() {
let empty = Cart()
print("Empty: \(Int(empty.total()))")
let apple = LineItem("Apple", 5.0, 3)
print("Subtotal: \(Int(apple.subtotal()))")
let cart = Cart()
cart.add(apple)
cart.add(LineItem("Bread", 20.0, 3))
print("Total: \(Int(cart.total()))")
cart.add(LineItem("Milk", 10.0, 2))
print("Total: \(Int(cart.total()))")
}
}
Details worth knowing
- No implicit numeric conversion.
price * quantitywith aDoubleand anIntdoesn't compile: the compiler reportscannot convert value of type 'Int' to expected argument type 'Double'.Double(quantity)is the fix. letproperties. They are set once in the initializer. Assigning to one later, as initem.price = 6, fails withcannot assign to property: 'price' is a 'let' constant.self.in the initializer. It is needed only because the parameters have the same names as the properties. Inside the initializer, a barenamemeans the parameter, so the property needsself.to be named.- The array is private, the rows are shared. Outside code can't touch
items, butLineItemis a class, so the apple the driver adds is the same object the cart holds. Since its properties are constants, that sharing can't cause surprises. - The driver prints
Int(...). Without it the totals would print as95.0.
Complexity
With n rows, total() visits each once, so it takes O(n) time and O(1) extra space for sum. add is amortized O(1). The cart uses O(n) space for its rows. Recomputing the total on every call costs a little time, but it can never disagree with the cart's contents.
Edge cases and common mistakes
- The empty cart. The loop body never runs, so
total()returns the starting 0.0. This is whysumstarts at 0.0 and not at the first item's subtotal. - Starting
sumas0.var sum = 0makes it anInt, and adding aDoublesubtotal to it doesn't compile. Writing0.0makes it aDouble. - Returning inside the loop. A
return sumplaced within the braces would end the method after the first row. - Forgetting
Double(quantity). This is the compile error above. - Non-whole prices. The driver uses whole numbers, but with a price of 1.5 and quantity 3 the subtotal is 4.5, and
Int(...)would print 4. A price of 0.1 with quantity 3 gives 0.30000000000000004, becauseDoublecan't represent 0.1 exactly. - Stale totals. Caching the total in a property and forgetting to update it in
addshows the old number after an item is added. Recomputing avoids that.
Testing
Print the totals as Doubles to see what the cart really holds:
let cart = Cart()
cart.add(LineItem("Apple", 5.0, 3))
cart.add(LineItem("Bread", 20.0, 3))
cart.add(LineItem("Milk", 10.0, 2))
print(cart.total())
let c2 = Cart()
c2.add(LineItem("Pen", 1.5, 3))
print(c2.total(), Int(c2.total()))
95.0
4.5 4
The first line is the lesson's full cart before Int(...) trims it. The second shows how Int(...) truncates a fractional total.
