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:
targetsare the modules. Each has a folder inSources/with the same name.productsare what the app is allowed to import. The app target addsProfileFeatureunder Frameworks, Libraries, and Embedded Content.dependencies: ["DesignSystem", "Networking"]saysProfileFeaturemayimport DesignSystem. Without it, the import fails.publicon the struct, itsinitandbodylets other modules use the button. Everything else stays private to the module.bundle: .modulefinds 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 explicitpublic 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 assumesBundle.mainbreaks silently, showing an empty image or the raw key. @testable importonly works for modules built with testing enabled (Debug), which is the default for package test targets.- Access levels:
privateandfileprivatestay within a file,internalwithin a module,packagewithin a package,publicfor clients, andopenalso allows subclassing and overriding outside the module. - Remote dependencies (Firebase, analytics SDKs) should be wrapped by one module (
Analyticsexposing a protocol), so only that module imports the SDK and the rest of the graph doesn’t rebuild or link it.
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")Hint: Which access level does Swift give the initializer it generates for a struct?
The compiler says “‘User’ initializer is inaccessible due to ‘internal’ protection level”. Swift generates a memberwise initializer for every struct, but it is always internal, even when the struct is public. Other modules can see the type and its properties, but can’t create one.
Write the initializer yourself and mark it public:
public struct User {
public let id: UUID
public let name: String
public init(id: UUID, name: String) {
self.id = id
self.name = name
}
}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.
- Create the package. File → New → Package, name it
AppModules, save it inPackages/and add it to the project. Add the package’sDesignSystemproduct to the app target. - Move the files. Drag
Colors.swift,PrimaryButton.swiftand theDesignSystem.xcassetscatalog intoSources/DesignSystem/(the asset catalog into aResourcesfolder listed inPackage.swift). - Build and read the errors. In the app, add
import DesignSystemwhere the button is used. Then mark the button, itsinitand itsbodypublic. - Fix the colors.
Color("Brand")now looks in the app’s bundle and finds nothing. Change it toColor("Brand", bundle: .module)inside the package. - Add a preview inside the package. A
#PreviewinPrimaryButton.swiftnow 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?
Image("name") looks in the main bundle, which belongs to the app. The image now lives in the package's bundle, so it isn't found: no build error, just an empty view and a console warning. Use Image("placeholder-avatar", bundle: .module) inside the package.
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:
ProfileInterfacecontains a protocol (or a small client struct) and route types;ProfileFeatureimplements it; Checkout depends only on the interface. Changes inside ProfileFeature no longer rebuild Checkout. - Shared domain models go in a core
Modelsmodule, 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;
packageaccess shares inside a package without goingpublic. - Public value types need an explicit
public init(memberwise inits are internal).openfor cross-module subclassing. - Resources:
Bundle.module; anything assumingBundle.mainsilently fails. - Wrap third-party SDKs behind one module’s protocol; features communicate via closures, routes or interface modules.
Check this part
Which import is a problem in a modular app?
A public struct in a package has no init written. Can the app create it?
Checkout needs to show a Profile screen. What keeps the modules decoupled?
Image("logo") inside a package can’t find the image in the package’s asset catalog. Why?