Skip to content
Commitwise
Menu
iOS Development

Modularization with Swift packages

Split a growing iOS app into local Swift packages, choose what is public, keep features from depending on each other, and understand what modules do to build times, previews, tests, app size and launch time.

advanced

The core idea with one simple example.Step by step, with more examples and exercises.A cheat sheet: key APIs, gotchas and trade-offs.Internals, trade-offs and production pitfalls.

The app started as one Xcode target. Three years and eight developers later it has 300,000 lines of Swift, a clean build takes eleven minutes, SwiftUI previews time out, and changing a color in the design system rebuilds everything. Two features import each other’s view models “just for one type”, and nobody can open the checkout screen in isolation to work on it.

Modularization means splitting the app into separate modulesModuleA unit of code compiled on its own and imported by name, such as an app target, a framework or a Swift package target.Open in glossary → with clear boundaries: a design system, networking, one module per feature. On iOS today the usual tool is local Swift packages, managed by Swift Package ManagerSwift Package ManagerSwift's built-in tool for packages: folders with a Package.swift that declares targets, products and dependencies.Open in glossary →, inside the repository. Done well, it gives faster incremental builds, previews that work, and teams that can change their feature without breaking someone else’s. Done badly, it gives the same tangle with extra public keywords.

New to some of these? Open what you need, or skip ahead.

Basics:What is a module?

A module is a unit of code that is compiled on its own and imported by name: import SwiftUI imports Apple’s SwiftUI module. Your app target is a module too. Types and functions are internal by default, which means visible only inside their own module. To use something from another module, it has to be marked public.

Basics:What is Swift Package Manager?

Swift Package Manager (SPM) is Swift’s built-in tool for packages. A package is a folder with a Package.swift file that lists its targets (modules with source code), its products (what others can import) and its dependencies (other packages). Xcode opens packages directly, and an app can use packages from GitHub or local packages that live in the same repository.

Part Not started

Splitting the app into packages

Think of a big kitchen. If every cook uses every drawer, nobody can find anything and two cooks always need the same knife. Give each station its own counter, with a few shared tools everyone may use, and the kitchen gets faster.

A modular app works the same way. The usual layout has three layers:

  • The app target: small. It creates the shared objects and connects the features. This is the only place that knows about every feature.
  • Feature modules: Profile, Checkout, Search. Each owns its screens and view models.
  • Core modules: DesignSystem (colors, buttons), Networking, Models. Features use these.

The rule that makes it work: arrows point down. Features may use core modules. Core modules never import features. Features never import each other.

A typical graph is three layers: a thin app target (composition root and navigation wiring), feature modules (UI, view models, feature logic), and core/foundation modules (DesignSystem, Networking, Persistence, domain Models, Analytics interfaces). Keep the graph acyclic and directed downwards; SPM rejects cycles, but the real damage is horizontal edges between features, which couple release cadence, ownership and build invalidation. A local package per area (Packages/Core, Packages/Features) with many targets is easier to manage than one package per module, and package access (Swift 5.9) lets modules in the same package share helpers without making them public to the app.

// Packages/AppModules/Package.swift
// swift-tools-version: 6.0
import PackageDescription

let package = Package(
    name: "AppModules",
    platforms: [.iOS(.v17)],
    products: [
        .library(name: "DesignSystem", targets: ["DesignSystem"]),
        .library(name: "Networking", targets: ["Networking"]),
        .library(name: "ProfileFeature", targets: ["ProfileFeature"]),
    ],
    targets: [
        .target(name: "DesignSystem", resources: [.process("Resources")]),
        .target(name: "Networking"),
        .target(name: "ProfileFeature", dependencies: ["DesignSystem", "Networking"]),
        .testTarget(name: "ProfileFeatureTests", dependencies: ["ProfileFeature"]),
    ]
)
// Sources/DesignSystem/PrimaryButton.swift
import SwiftUI

public struct PrimaryButton: View {
    let title: String
    let action: () -> Void

    public init(_ title: String, action: @escaping () -> Void) {   // public init: see below
        self.title = title
        self.action = action
    }

    public var body: some View {
        Button(title, action: action)
            .buttonStyle(.borderedProminent)
            .tint(Color("Brand", bundle: .module))                    // the package's own asset catalog
    }
}

What each piece does:

  • targets are the modules. Each has a folder in Sources/ with the same name.
  • products are what the app is allowed to import. The app target adds ProfileFeature under Frameworks, Libraries, and Embedded Content.
  • dependencies: ["DesignSystem", "Networking"] says ProfileFeature may import DesignSystem. Without it, the import fails.
  • public on the struct, its init and body lets other modules use the button. Everything else stays private to the module.
  • bundle: .module finds the color in the package’s own resources, not in the app’s.

To create one in Xcode: File → New → Package, save it in the repository (for example in Packages/), and add it to the app project. Then move files into Sources/<Module>/ and fix the errors one by one: most are “cannot find in scope” (add an import) or “inaccessible due to internal protection level” (add public).

Details that bite:

  • Structs’ memberwise initializers are internal, even for a public struct. Every public value type needs an explicit public init.
  • Resources (asset catalogs, JSON, localized strings) live in the target’s own bundle: Bundle.module, Image("x", bundle: .module), String(localized:bundle:). Code that assumes Bundle.main breaks silently, showing an empty image or the raw key.
  • @testable import only works for modules built with testing enabled (Debug), which is the default for package test targets.
  • Access levels: private and fileprivate stay within a file, internal within a module, package within a package, public for clients, and open also allows subclassing and overriding outside the module.
  • Remote dependencies (Firebase, analytics SDKs) should be wrapped by one module (Analytics exposing a protocol), so only that module imports the SDK and the rest of the graph doesn’t rebuild or link it.
Spot the bugThe app can't create a user

Tap the line with the bug.

// In the Models package
public struct User {
    public let id: UUID
    public let name: String
}

// In the app target
import Models

let user = User(id: UUID(), name: "Ana")

Practice: extract the design system

The design system is the best first module: almost every screen uses it, and it depends on nothing else in the app.

  1. Create the package. File → New → Package, name it AppModules, save it in Packages/ and add it to the project. Add the package’s DesignSystem product to the app target.
  2. Move the files. Drag Colors.swift, PrimaryButton.swift and the DesignSystem.xcassets catalog into Sources/DesignSystem/ (the asset catalog into a Resources folder listed in Package.swift).
  3. Build and read the errors. In the app, add import DesignSystem where the button is used. Then mark the button, its init and its body public.
  4. Fix the colors. Color("Brand") now looks in the app’s bundle and finds nothing. Change it to Color("Brand", bundle: .module) inside the package.
  5. Add a preview inside the package. A #Preview in PrimaryButton.swift now builds only the design system, so it renders fast.

Predict the output

After moving Avatar.swift into the DesignSystem package, the code still says Image("placeholder-avatar"), and the image is in the package's asset catalog. What appears on screen?

Feature-to-feature communication

When Checkout needs to open Profile, don’t add an edge between them. Options, from simplest:

  • Closures or a route enum passed in from the app target: CheckoutView(onEditAddress: { router.push(.profile(.address)) }). The app target is the only place that knows both.
  • Interface modules: ProfileInterface contains a protocol (or a small client struct) and route types; ProfileFeature implements it; Checkout depends only on the interface. Changes inside ProfileFeature no longer rebuild Checkout.
  • Shared domain models go in a core Models module, not in whichever feature created them first.
  • Layers: thin app target (composition root, navigation wiring) → feature modules → core modules. Acyclic, downward edges only; no feature → feature imports.
  • Local packages with many targets; package access shares inside a package without going public.
  • Public value types need an explicit public init (memberwise inits are internal). open for cross-module subclassing.
  • Resources: Bundle.module; anything assuming Bundle.main silently fails.
  • Wrap third-party SDKs behind one module’s protocol; features communicate via closures, routes or interface modules.

Check this part

  1. Which import is a problem in a modular app?

  2. A public struct in a package has no init written. Can the app create it?

  3. Checkout needs to show a Profile screen. What keeps the modules decoupled?

  4. Image("logo") inside a package can’t find the image in the package’s asset catalog. Why?

Move code into local Swift packages: one target per module, a library product for each module the app imports, and dependencies that point downwards (features depend on core modules like DesignSystem and Networking, never on each other). Anything used across modules must be public, including initializers; package access shares code inside one package only. Resources need Bundle.module.

Part Not started

Build times, previews and linking

Modules make builds faster because Xcode only rebuilds what changed and what depends on it:

  • Change a file in ProfileFeature: only ProfileFeature and the app rebuild.
  • Change DesignSystem: every feature that uses it rebuilds, because they all depend on it.

So the modules lower in the graph should change rarely. A design system that changes every day is fine in a small app, but in a big one it’s worth keeping stable.

Two more wins you’ll notice right away:

  • Previews inside a package only build that package, so they start in seconds.
  • Tests for a module run without launching the whole app.

Incremental build cost is the change’s module plus all its dependents, so build time is shaped by the graph: keep high-churn code (features) at the top and stable code (foundation) at the bottom, and prefer a wide graph to a deep chain, since independent modules compile in parallel. Interface modules cut invalidation further: dependents recompile only when the interface changes. Measure with Xcode’s Build Timeline (Report navigator → Build → Timeline) and -Xfrontend -warn-long-function-bodies=200 for type-checking hot spots. Xcode 16’s explicitly built modules make module builds more parallel and cacheable. Above a few hundred modules, teams usually generate projects (Tuist, XcodeGen) or move to Bazel for remote caching.

Linking. A Swift package library product with automatic type is linked statically (static vs dynamic linkingStatic vs dynamic linkingStatic linking copies a library's code into each binary that uses it; dynamic linking loads one shared copy at runtime.Open in glossary →) into whatever uses it. Static linking means no extra dylib to load at launch (each dynamic framework costs launch time), and the linker can strip unused code. The catch: if the same static module is linked into two binaries, such as the app and a widget extension, or two dynamic frameworks loaded in one process, its code and its globals exist twice. Two copies of a “shared” singleton or cache is a real production bug. Options: make the shared module a .dynamic product (one copy, small launch cost), keep shared state out of statics, or use Xcode’s mergeable libraries, which are dynamic in debug (fast iteration) and merged into the app binary in release.

// Package.swift: an explicitly dynamic product, shared by the app and its extensions
products: [
    .library(name: "SharedStore", type: .dynamic, targets: ["SharedStore"]),
    .library(name: "DesignSystem", targets: ["DesignSystem"]),   // automatic: static in practice
],
# Find slow-to-type-check functions in one module (add to the target's Other Swift Flags)
-Xfrontend -warn-long-function-bodies=200
-Xfrontend -warn-long-expression-type-checking=200

# Compare app size before and after a change
xcodebuild -scheme App -configuration Release archive -archivePath build/App.xcarchive
du -sh build/App.xcarchive/Products/Applications/App.app

Production puzzles

Predict the output

An Analytics module (a static library with a shared singleton holding the user id) is linked into the app and into a dynamic framework, Payments, that the app also embeds. The app sets Analytics.shared.userId at login. Payments sends events with Analytics.shared.userId. What does Payments send?

Spot the bugOne small change rebuilds everything

Tap the line with the bug.

// Package.swift (excerpt)
.target(name: "Models"),
.target(name: "Networking", dependencies: ["Models"]),
.target(name: "AppConfig", dependencies: ["Models"]),     // feature flags, edited daily
.target(name: "DesignSystem", dependencies: ["AppConfig"]),
.target(name: "ProfileFeature", dependencies: ["DesignSystem", "Networking"]),
.target(name: "CheckoutFeature", dependencies: ["DesignSystem", "Networking"]),
.target(name: "SearchFeature", dependencies: ["DesignSystem", "Networking"]),

Exercisehard

Plan the split

A 300,000-line single-target app, 8 developers in 3 teams (Shopping, Account, Platform), an 11-minute clean build and a widget extension. Outline the module plan, the order of extraction, and how you’ll know it worked.

›

Start where the payoff is highest and the risk lowest, and decide what you’ll measure before you move a single file.

SolutionTry it yourself first
  1. Measure first: clean and incremental build times (Build Timeline), test time, app size, launch time. These are the success criteria.
  2. Extract leaves first: Models, DesignSystem, Networking, Persistence, then an Analytics interface wrapping the SDKs. They have no app dependencies, so the moves are mechanical.
  3. Then features by team ownership: Shopping* and Account* modules, each with its own tests and preview app. Cross-feature calls become closures or interface modules wired in the app target. Add a CI check (a script over Package.swift) that fails on feature → feature edges.
  4. Shared code with the widget: anything both the app and the widget use (the store, models) is either a dynamic product or carefully stateless, to avoid duplicated singletons.
  5. Track the numbers after each step. Incremental build time on a typical change should drop the most; clean build time may barely move, and that’s fine.
Exerciseeasy

Draw the graph

A recipe app has: a design system, an API client, recipe models, a Recipes feature (list and detail), a Favorites feature and a Shopping List feature. Favorites shows recipe cards; the Shopping List can open a recipe. Which module depends on which?

›

Where should the recipe card live so that both Recipes and Favorites can use it without importing each other?

SolutionTry it yourself first
  • Core: Models (Recipe), APIClient → Models, DesignSystem (with a RecipeCard view that takes plain values or a Recipe from Models).
  • Features: RecipesFeature, FavoritesFeature, ShoppingListFeature, each → DesignSystem, APIClient, Models.
  • App target → all three features. It gives the Shopping List a closure onOpenRecipe: (Recipe.ID) -> Void that pushes the Recipes detail screen.

No feature imports another one: the shared card moved down into DesignSystem, and navigation goes through the app.

  • Incremental cost = changed module + all dependents. Volatile code high, stable code low; wide graphs build in parallel; interface modules limit invalidation.
  • Measure: Build Timeline, -warn-long-function-bodies, app size, launch time. Tuist, XcodeGen or Bazel beyond a few hundred modules.
  • Package libraries link statically by default: faster launch, dead-code stripping, but duplicated code and globals when linked into several binaries (app + extension, two dynamic frameworks).
  • Shared state across binaries: .dynamic product, injection, or mergeable libraries (dynamic in debug, merged in release).

Check this part

  1. You change a file in DesignSystem. What rebuilds?

  2. Why do previews get faster in a small package?

  3. A static module with a singleton is linked into the app and a widget extension. How many singletons exist?

  4. Where should a module edited every day sit in the dependency graph?

A change rebuilds its module and everything that depends on it, so keep frequently changing code high in the graph and the graph wide rather than deep. Small modules make previews and tests fast. Package libraries are usually linked statically into the app: fast launch, but a static module linked into several dynamic frameworks or extensions is duplicated, including its singletons. Measure build times and app size before and after.

Key takeaways

  • Split the app into core modules (design system, networking, models) and feature modules, connected by a small app target.
  • Dependencies point down; features never import each other.
  • Anything used from another module must be public, including struct initializers.
  • Package resources are in Bundle.module.
  • Shape the graph for build invalidation: volatile code high, stable code low, wide not deep, interface modules where it matters.
  • Wrap third-party SDKs; wire features together only in the app target.
  • Static linking is the default and usually right, but never duplicate stateful modules across binaries.
  • Measure build times, size and launch before and after; it’s an engineering investment, not a style choice.

Finished this page?Nice work, this page is complete!

Mark it as done to track your progress. It's saved in this browser, no account needed.

Its cards are now in your Bites review ⚡
Esc

Type to search the whole site.