Start learning free

LESSON 68 OF 71 · PROJECTS: OBJECT-ORIENTED

Shopping Cart in Swift: LineItem and Cart Classes

Practice Read the full explanation

A shop keeps its orders in a cart. Build two classes that work together: a LineItem is one row of the cart (a product, its price and how many were bought), and a Cart holds many rows and adds them up. The cart has line items (composition), it is not one.

LineItem

  • Constants let name: String, let price: Double, let quantity: Int.
  • init(_ name: String, _ price: Double, _ quantity: Int) stores the three values with self..
  • func subtotal() -> Double returns price * Double(quantity) (convert the Int first, Swift won't mix the types).

Cart

  • It keeps its items in private var items = [LineItem]().
  • func add(_ item: LineItem) appends the item to the array.
  • func total() -> Double returns the sum of the subtotals of all items: start var sum = 0.0, loop with for item in items, return sum.

Rules:

  • The total is worked out every time it is asked for, from the items in the cart at that moment. Adding an item later changes the next total.
  • An empty cart has a total of 0.
  • An item with price 5 and quantity 3 has a subtotal of 15.
  • Prices in the driver are whole numbers.

The driver lives in Solution.mainFunction() and prints Int(...) to show whole numbers.

The driver (already in the starter code, don't change it) creates an empty cart, checks one subtotal, then fills a cart and prints the total twice:

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()))")
    }
}

Expected output:

Empty: 0
Subtotal: 15
Total: 75
Total: 95

Write LineItem (properties, init, subtotal) first, then Cart.

for item in items { sum += item.subtotal() }

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()))")
    }
}

STEP 1 OF 19
    Ctrl + Enter to check

    SWIFT · PROJECTS: OBJECT-ORIENTED

    Shopping Cart in Swift, explained

    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

    1. Declare LineItem and write its closing brace right away.
    2. Add let name: String. It is let because a row's values never change once it is made.
    3. Add let price: Double. A Double holds decimals, in case a price isn't whole.
    4. Add let quantity: Int. The number bought is always whole.
    5. Write the initializer. Each parameter gets an underscore before its name, so the driver can write LineItem("Apple", 5.0, 3) without labels.
    6. Store the name in self.name. The parameter and the property share a name, so self. says which one is the property.
    7. Store the price in self.price.
    8. Store the quantity in self.quantity. Now a row remembers all three values.
    9. Start subtotal, returning a Double.
    10. Return price * Double(quantity). Swift won't multiply a Double by an Int, so the quantity is converted first.
    11. Declare Cart below LineItem.
    12. Add the storage private var items = [LineItem](). It is var because the array grows as rows come in.
    13. Start add, taking a LineItem named item with an underscore label.
    14. Append the item to items. The array keeps rows in the order they arrived.
    15. Start total, returning a Double.
    16. Create var sum = 0.0. Starting at zero is what makes an empty cart total 0.
    17. Loop with for item in items. No index is needed, since the loop hands over each row.
    18. Add the row's subtotal to sum, by asking item.subtotal().
    19. Return sum after 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 * quantity with a Double and an Int doesn't compile: the compiler reports cannot convert value of type 'Int' to expected argument type 'Double'. Double(quantity) is the fix.
    • let properties. They are set once in the initializer. Assigning to one later, as in item.price = 6, fails with cannot 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 bare name means the parameter, so the property needs self. to be named.
    • The array is private, the rows are shared. Outside code can't touch items, but LineItem is 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 as 95.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 why sum starts at 0.0 and not at the first item's subtotal.
    • Starting sum as 0. var sum = 0 makes it an Int, and adding a Double subtotal to it doesn't compile. Writing 0.0 makes it a Double.
    • Returning inside the loop. A return sum placed 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, because Double can't represent 0.1 exactly.
    • Stale totals. Caching the total in a property and forgetting to update it in add shows 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.

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