Three Levels of Modularizing an Old UIKit Project

Modularizing an iOS project is more than moving to SPM. Nested UI components, view models with controlled doors, and packages that own their dependencies, with what worked and what I left unfinished at each level.

On this page
  1. Level 1: UI components that nest
  2. Level 2: view models with controlled doors
  3. Level 3: packages that own their dependencies
  4. Where it ended up

When people talk about modularizing an iOS project, the conversation usually jumps straight to Swift Package Manager. In the old UIKit project I worked on, packages were only the last of three levels. The same two questions came up at each one: where does the boundary go, and who is allowed to go through it, and by which door?

The code below is rewritten from what I did, with the names and business details changed.

Level 1: UI components that nest

A screen isn’t one view. It’s small elements assembled into cards, and cards assembled into a page. So I build from the smallest piece up, and each piece declares its own Content: the data it needs to display.

final class QuantityTagView: UIView {
    struct Content {
        let quantity: Int
    }

    private let label = UILabel()

    func configure(with content: Content) {
        label.text = "x \(content.quantity)"
    }
}

A card doesn’t reach into its children. Its Content holds their Content, and it passes each one down.

final class TicketCardView: UIView {
    struct Content {
        let title: String
        let expiryTag: ExpiryTagView.Content?
        let quantityTag: QuantityTagView.Content
    }

    private let titleLabel = UILabel()
    private let expiryTagView = ExpiryTagView()
    private let quantityTagView = QuantityTagView()

    func configure(with content: Content) {
        titleLabel.text = content.title
        expiryTagView.isHidden = content.expiryTag == nil
        if let expiryTag = content.expiryTag {
            expiryTagView.configure(with: expiryTag)
        }
        quantityTagView.configure(with: content.quantityTag)
    }
}

The view model sits at the top of the nesting. It turns an API response into one big Content value, and the page hands it down.

Because each level only needs its own Content, each level can be previewed alone, with no network and no app startup. A small element gets its own preview. So does the card, and each state gets a separate preview rather than being crammed into one.

#Preview("Expiring soon") {
    let card = TicketCardView()
    card.configure(with: .init(
        title: "Sample ticket",
        expiryTag: .init(daysLeft: 3),
        quantityTag: .init(quantity: 2)
    ))
    return card
}

#Preview("No expiry") {
    let card = TicketCardView()
    card.configure(with: .init(
        title: "Sample ticket",
        expiryTag: nil,
        quantityTag: .init(quantity: 1)
    ))
    return card
}

The demo repo shows this on a small product page, with one preview per state. It’s a simplified example, not production code.

The demo product page in five states: in stock, sold out, out of stock, restocking, and an API error alert.

I didn’t apply this cleanly everywhere. I defined a protocol to standardize configure(with:), and no component ended up conforming to it. Some composite views still accept an API model directly, and some Content factories read API types, so the mapping sits next to the view.

Level 2: view models with controlled doors

A view model has state, and old code tends to let anyone change it. I treat it like a small room: state is private, reads go out through one door, and changes come in through named methods. Swift’s access control makes the compiler enforce this.

final class ProductListViewModel {
    private var allProducts: [Product] = []
    private let productsRelay = PublishRelay<[Product]>()

    private(set) var sortOrder: SortOrder = .newestFirst

    var products: Observable<[Product]> {
        productsRelay.asObservable()
    }

    func updateSortOrder(_ order: SortOrder) {
        sortOrder = order
        productsRelay.accept(sorted(allProducts, by: order))
    }
}

The screen can read sortOrder but can’t assign it. It can observe products but can’t push values into them. If the list changes, there’s only one place to look.

The same idea applies to views. On a quantity control, callers used to reach straight into the buttons:

cell.quantityView.plusButton.isEnabled = canAddMore

So I made the buttons and the text field private and exposed only what callers needed:

cell.quantityView.plusButtonIsEnabled = canAddMore

It looks like a small change, but now the control owns its internals. Inside it, the quantity also has two separate doors. Setting it from user input clamps the value and fires a callback. Setting the initial value from data doesn’t fire the callback. Without that split, loading a screen would look like a user edit.

final class QuantityControlView: UIView {
    private var quantity = 1
    var onQuantityChange: ((Int) -> Void)?

    // For data: no callback.
    var initialQuantity: Int {
        get { quantity }
        set { quantity = clamped(newValue) }
    }

    // For user input: clamps and notifies.
    private func userDidChangeQuantity(to newValue: Int) {
        quantity = clamped(newValue)
        onQuantityChange?(quantity)
    }

    private func clamped(_ value: Int) -> Int { max(1, value) }
}

This wasn’t complete either. Some view models I wrote still expose a relay directly, which means any caller can push a value into it. That’s a door I should have closed.

Level 3: packages that own their dependencies

The last level is the project itself. On a refactor branch, I moved shared logic into local Swift Packages inside the repo. The rule I wrote down for it was: SPM is only the delivery mechanism. A package that exposes third-party types isn’t a real boundary, even if it has a Package.swift.

So the package owns the dependency, and access control decides what the app can see.

import Alamofire

public final class Session {
    private let underlying: Alamofire.Session

    internal init(underlying: Alamofire.Session) {
        self.underlying = underlying
    }

    public func request(_ url: URL, method: HTTPMethod = .get) -> DataRequest {
        DataRequest(underlying: underlying.request(url, method: method.alamofireValue))
    }
}

Three keywords do the work. The class is public, so the app can use it. The wrapped session is private, so the app never touches Alamofire’s type. The initializer is internal, so only a factory in the package can create one.

On that branch, no file in the app imported the networking, logging, or analytics libraries directly. They imported our packages instead. If a vendor changed, the app shouldn’t need to know.

I missed one spot: a public initializer on an error wrapper still takes the library’s error type, so a little of the vendor leaked through.

Where it ended up

The full version of level 3 never shipped. The release branch went back to CocoaPods. A few small packages stayed, and the three wrapper packages stayed on the refactor branch.

The thinking doesn’t depend on the package manager, though. Nesting components, closing doors on a view model, and letting one module own a dependency can all be done in an old project one screen at a time, without migrating anything.