Start learning free

LESSON 413 OF 415 · PROJECTS: OBJECT-ORIENTED

Shopping Cart in Swift in Swift

Practice

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

    Shopping Cart in Swift

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