Project 7: Shopping App with Products and a Cart

iOS App Development with Swift and SwiftUI: 13 Projects · More Real-World iOS Projects · 16 min read · Updated

Browse, add, pay on a server

  1. Products load from the API into the view model.
  2. Add to cart puts a line in the cart with the price in cents.
  3. Both tabs read the same cart, so totals and the badge always agree.
  4. In a real shop, checkout sends the cart to your server, which takes payment through a provider.

Shopping apps are a favourite interview project because they combine a network list, images, shared state between two screens and exact money. This project builds the core of one. Products come from the Fake Store API, the cart is saved on the phone, and the checkout is a demo that empties the cart and takes no payment.

A real shop needs a sign-in, addresses, a server that creates orders, a payment provider and legal pages. The lesson points to where each of these would go, but it does not pretend that a demo is a finished shop. Never put card numbers into your own screens. Use Apple Pay or a payment provider's hosted checkout and confirm the order on your server.

Concepts in this project

  • Exact money: prices become whole cents the moment a product enters the cart, and totals are sums of integers.
  • A shared store: one CartStore object is passed to both tabs, so the badge, the list and the total always agree.
  • Computed values: totalCents and itemCount are calculated from the lines, so they cannot go out of date.
  • TabView with a badge: the Cart tab shows the number of items.
  • LazyVGrid with adaptive columns: the grid fits two columns on a phone and more on an iPad.
  • Extension for formatting: Int.asMoney turns 4990 into $49.90.

Create the project

  1. In Xcode choose File > New > Project > iOS > App. Set Interface to SwiftUI, Language to Swift, and Testing System to Swift Testing. Set the minimum deployment to iOS 17, because the code uses @Observable. Name the product MiniShop.
  2. Delete the default ContentView.swift and the default @main file, then add the files below.
MiniShop/
  ShopApp.swift        @main
  Product.swift        Product, CartLine, money format
  CartStore.swift      cart saved as JSON
  ShopViewModel.swift  loading products
  ShopViews.swift      tabs, grid, cart
MiniShopTests/
  ShopTests.swift

The code

`Product.swift`

import Foundation

struct Product: Identifiable, Codable, Hashable {
    let id: Int
    let title: String
    let price: Double
    let description: String
    let category: String
    let image: URL

    // Money is kept in whole cents everywhere in the cart, so there are no rounding surprises.
    var priceCents: Int { Int((price * 100).rounded()) }
}

struct CartLine: Identifiable, Codable, Equatable {
    let productID: Int
    let title: String
    let priceCents: Int
    var quantity: Int

    var id: Int { productID }
    var lineTotalCents: Int { priceCents * quantity }
}

extension Int {
    // 4990 -> "$49.90"
    var asMoney: String {
        let sign = self < 0 ? "-" : ""
        let value = abs(self)
        return "\(sign)$\(value / 100).\(String(format: "%02d", value % 100))"
    }
}

`CartStore.swift`

import Foundation
import Observation

@Observable
final class CartStore {
    private let defaults: UserDefaults

    private(set) var lines: [CartLine] {
        didSet { save() }
    }

    init(defaults: UserDefaults = .standard) {
        self.defaults = defaults
        if let data = defaults.data(forKey: "cart.v1"),
           let saved = try? JSONDecoder().decode([CartLine].self, from: data) {
            lines = saved
        } else {
            lines = []
        }
    }

    var totalCents: Int { lines.reduce(0) { $0 + $1.lineTotalCents } }
    var itemCount: Int { lines.reduce(0) { $0 + $1.quantity } }

    func add(_ product: Product) {
        if let index = lines.firstIndex(where: { $0.productID == product.id }) {
            lines[index].quantity += 1
        } else {
            lines.append(CartLine(productID: product.id, title: product.title,
                                  priceCents: product.priceCents, quantity: 1))
        }
    }

    func change(_ line: CartLine, by delta: Int) {
        guard let index = lines.firstIndex(where: { $0.productID == line.productID }) else { return }
        lines[index].quantity += delta
        if lines[index].quantity <= 0 { lines.remove(at: index) }
    }

    // Demo only: this clears the cart and takes no payment.
    func placeDemoOrder() {
        lines = []
    }

    private func save() {
        if let data = try? JSONEncoder().encode(lines) {
            defaults.set(data, forKey: "cart.v1")
        }
    }
}

`ShopViewModel.swift`

import Foundation
import Observation

@Observable
@MainActor
final class ShopViewModel {
    enum State {
        case loading
        case ready([Product])
        case failed(String)
    }

    private(set) var state: State = .loading

    func load() async {
        state = .loading
        do {
            guard let url = URL(string: "https://fakestoreapi.com/products") else { return }
            let (data, response) = try await URLSession.shared.data(from: url)
            if let http = response as? HTTPURLResponse, !(200..<300).contains(http.statusCode) {
                state = .failed("The shop answered with error \(http.statusCode).")
                return
            }
            state = .ready(try JSONDecoder().decode([Product].self, from: data))
        } catch {
            state = .failed("Could not load products. Check your connection and try again.")
        }
    }
}

`ShopViews.swift`

import SwiftUI

struct ShopRootView: View {
    @State private var cart = CartStore()
    @State private var shop = ShopViewModel()

    var body: some View {
        TabView {
            ProductGridView(shop: shop, cart: cart)
                .tabItem { Label("Shop", systemImage: "bag") }
            CartView(cart: cart)
                .tabItem { Label("Cart", systemImage: "cart") }
                .badge(cart.itemCount)
        }
        .task { await shop.load() }
    }
}

struct ProductGridView: View {
    let shop: ShopViewModel
    let cart: CartStore
    private let columns = [GridItem(.adaptive(minimum: 150), spacing: 12)]

    var body: some View {
        NavigationStack {
            Group {
                switch shop.state {
                case .loading:
                    ProgressView("Loading products...")
                case .failed(let message):
                    VStack(spacing: 12) {
                        Text(message).multilineTextAlignment(.center)
                        Button("Try again") { Task { await shop.load() } }
                            .buttonStyle(.borderedProminent)
                    }
                    .padding()
                case .ready(let products):
                    ScrollView {
                        LazyVGrid(columns: columns, spacing: 12) {
                            ForEach(products) { product in
                                ProductCard(product: product) { cart.add(product) }
                            }
                        }
                        .padding()
                    }
                }
            }
            .navigationTitle("Shop")
        }
    }
}

struct ProductCard: View {
    let product: Product
    let onAdd: () -> Void

    var body: some View {
        VStack(alignment: .leading, spacing: 6) {
            AsyncImage(url: product.image) { image in
                image.resizable().scaledToFit()
            } placeholder: {
                ProgressView()
            }
            .frame(height: 110)
            .frame(maxWidth: .infinity)
            Text(product.title)
                .font(.subheadline)
                .lineLimit(2)
            Text(product.priceCents.asMoney)
                .font(.headline)
            Button("Add to cart", action: onAdd)
                .buttonStyle(.borderedProminent)
                .controlSize(.small)
        }
        .padding(10)
        .background(Color(.secondarySystemBackground), in: RoundedRectangle(cornerRadius: 12))
    }
}

struct CartView: View {
    let cart: CartStore
    @State private var message: String?

    var body: some View {
        NavigationStack {
            Group {
                if cart.lines.isEmpty {
                    ContentUnavailableView("Your cart is empty", systemImage: "cart",
                                           description: Text(message ?? "Add something from the Shop tab."))
                } else {
                    List {
                        ForEach(cart.lines) { line in
                            HStack {
                                VStack(alignment: .leading) {
                                    Text(line.title).lineLimit(2)
                                    Text(line.lineTotalCents.asMoney).font(.caption)
                                }
                                Spacer()
                                Stepper("", onIncrement: { cart.change(line, by: 1) },
                                        onDecrement: { cart.change(line, by: -1) })
                                    .labelsHidden()
                                Text("\(line.quantity)").frame(minWidth: 24)
                            }
                        }
                        Section {
                            HStack {
                                Text("Total").font(.headline)
                                Spacer()
                                Text(cart.totalCents.asMoney).font(.headline)
                            }
                            Button("Place demo order") {
                                cart.placeDemoOrder()
                                message = "Demo order placed. No payment was taken."
                            }
                        }
                    }
                }
            }
            .navigationTitle("Cart")
        }
    }
}

`ShopApp.swift`

import SwiftUI

@main
struct ShopApp: App {
    var body: some Scene {
        WindowGroup {
            ShopRootView()
        }
    }
}

`ShopTests.swift (in the tests target)`

import Testing
import Foundation
@testable import MiniShop

struct ShopTests {
    private func product(_ id: Int, _ price: Double) -> Product {
        Product(id: id, title: "Item \(id)", price: price, description: "", category: "x",
                image: URL(string: "https://example.com/a.png")!)
    }

    // A throwaway store so tests never touch the real saved cart.
    private func store() -> CartStore {
        CartStore(defaults: UserDefaults(suiteName: UUID().uuidString)!)
    }

    @Test func priceBecomesExactCents() {
        #expect(product(1, 109.95).priceCents == 10995)
        #expect(product(2, 0.1).priceCents == 10)
    }

    @Test func addingTwiceRaisesQuantity() {
        let cart = store()
        cart.add(product(1, 10))
        cart.add(product(1, 10))
        #expect(cart.lines.count == 1)
        #expect(cart.itemCount == 2)
        #expect(cart.totalCents == 2000)
    }

    @Test func lessThanOneRemovesTheLine() {
        let cart = store()
        cart.add(product(1, 10))
        cart.change(cart.lines[0], by: -1)
        #expect(cart.lines.isEmpty)
    }

    @Test func moneyFormat() {
        #expect(4990.asMoney == "$49.90")
        #expect(5.asMoney == "$0.05")
    }
}

Walkthrough

Product mirrors the service's JSON, with the price as a Double because that is what the service sends. The computed property priceCents rounds price * 100 to the nearest whole number. Rounding matters: 109.95 times 100 is not exactly 10995 in floating point, so you must round, not truncate. From that point on, the cart never touches a Double again.

CartLine stores the product id, title, price in cents and quantity. It copies the title and price at the time of adding, which is how real carts work: a later price change should not silently change an order already in progress. lineTotalCents multiplies price by quantity.

CartStore is an @Observable class. The add function either raises the quantity of an existing line or appends a new one. change(_:by:) adjusts a quantity and removes the line when it reaches zero. Every change to lines triggers didSet, which encodes the cart to JSON and saves it to UserDefaults, so the cart survives closing the app.

In ShopRootView, both objects are created once with @State and passed down. .task { await shop.load() } loads the products when the view appears. The product grid reads the state with a switch: a spinner, a message with a Try again button, or the grid. .badge(cart.itemCount) puts the count on the Cart tab.

The tests use a throwaway UserDefaults suite with a random name, so they never touch the real saved cart. They check the cent conversion, that adding twice raises the quantity, that going below one removes the line, and the money format. Money code deserves tests more than almost any other code.

How it works

  • ShopViewModel.load fetches and decodes the product list from the service.
  • Add to cart calls cart.add(product), which updates or creates a line and saves it.
  • The cart screen reads cart.lines and shows steppers. Changes update the total at once.
  • Place demo order clears the cart and shows a message. No money moves.

Expected output

The Shop tab shows a grid of products with pictures, titles, prices and an Add to cart button. Add two products: the Cart tab shows a badge with 2. Open Cart: each row has a title, line price, a stepper and a quantity. Press the plus: the total rises. Reduce a line to zero: it disappears. Close the app and reopen it: the cart is still there. Place demo order: the cart empties and says "Demo order placed. No payment was taken." Turn on Airplane Mode before first launch and the Shop tab shows an error with a Try again button.

Your task

  1. Build the app and fill the cart with three products.
  2. Add a category filter built from the products' category field.
  3. Add a product detail screen with NavigationStack that shows the description.
  4. Save the cart with SwiftData instead of UserDefaults.

How to check it worked

  • Totals equal the sum of the lines.
  • The cart survives closing the app.
  • You can explain why payment must be confirmed on a server.

Next, try the same idea on another platform with the Android Development with Kotlin course, or go deeper on iOS with the Advanced iOS Development course.

Frequently asked questions

Why use cents?

Whole numbers add exactly. Floating point numbers can give totals such as 49.900000000000006.

Should the app decide the final price?

Only for display. The server must work out prices from its own data, because a changed app could send any price.

Can I take payments in this app?

Use Apple Pay or a payment provider and confirm the order on your server. Never collect or store card numbers yourself.