Skip to Content
Course content

247: Modularizing a Large Swift App with Swift Packages

Click on the "Edit" button in the top corner of the screen to edit your slide content.

I've been staring at the build times for our "ShopSwift" app, and frankly, it's getting ridiculous. Every time I change a single string in a view, Xcode seems to re-evaluate half the project. The problem is that we've let the app grow into a "monolith." The networking logic, the payment processing, and the UI theme are all shoved into the main app target. It's a big ball of mud.

Dealing with the Big Ball of Mud

Right now, my NetworkManager is sitting right next to my CheckoutViewController. It works, but there's no boundary. I can accidentally call a private networking method from a UI component, and the compiler doesn't care because they're in the same module. I want to carve the networking logic out into its own space so it can be tested in isolation and, more importantly, so Xcode doesn't have to recompile it every time I tweak a UI margin.

I'm going to try using a local Swift Package. I'll go to File > New > Package and call it CoreNetworking. I'll save it right inside the project folder so I don't have to deal with remote Git repositories while I'm just experimenting.

// Inside CoreNetworking/Sources/CoreNetworking/NetworkClient.swift
public class NetworkClient {
    public init() {}
    
    public func fetchItems() async throws -> [String] {
        // Imagine some URLSession logic here
        return ["Apple Watch", "MacBook Pro", "iPad Air"]
    }
}

I've added the CoreNetworking package to my app's target dependencies, but when I try to initialize NetworkClient() in my view controller, I hit a wall. Xcode screams at me: 'NetworkClient' initializer is not accessible from this scope. Ah, right. I forgot that when you move code into a separate module, the default access level is internal. In a monolith, everything is internal to the same app, so it's invisible. Now that it's in a package, I have to be explicit. I've added public to the class and the initializer, and now it finally compiles.

The Circular Dependency Trap

Now I want to move the PaymentService out too. I'll create another package called PaymentKit. I figure PaymentKit will need the NetworkClient to actually send the credit card data to the server, so I'll add CoreNetworking as a dependency of PaymentKit in the Package.swift file.

// PaymentKit/Package.swift
.target(
    name: "PaymentKit",
    dependencies: ["CoreNetworking"]
)

Everything seems fine until I realize that my NetworkClient needs to know about the APIKey, which is currently stored in a Configuration struct inside the main app. I try to import the main app into CoreNetworking... and the compiler completely loses its mind. I've created a circular dependency: the App depends on the Package, and the Package depends on the App. This is the classic "modularization trap."

I can't let the package depend on the app. Instead, I have to invert the dependency. I'll create a NetworkConfiguration protocol inside CoreNetworking. The package will define what it *needs*, and the app will provide the *actual* values.

// Inside CoreNetworking
public protocol NetworkConfiguration {
    var apiKey: String { get }
}

public class NetworkClient {
    private let config: NetworkConfiguration
    
    public init(config: NetworkConfiguration) {
        self.config = config
    }
}

Now, in the main app, I just make my app's config struct conform to that protocol. The package is now agnostic; it doesn't know the app exists, it just knows that whatever is calling it will provide an API key. This is much cleaner.

Observing the Win

Now that I've split the app into App $\rightarrow$ PaymentKit $\rightarrow$ CoreNetworking, I'm noticing something. When I change a line of code in PaymentKit, Xcode no longer needs to re-index or re-verify the CoreNetworking code. The boundaries are real. If I try to use a NetworkClient method that I didn't mark as public, the compiler stops me immediately. I've essentially forced myself to design a better API because I can no longer "cheat" by accessing internal variables from across the project.




📋 Practical Task

Exercise: Extracting the UserProfile Logic into a Local Package

You have a monolithic app with a UserProfileManager class that handles fetching user data and updating the local cache. Your goal is to modularize this to improve build times and separation of concerns.

  • Create a local Swift Package named UserIdentity.
  • Move the UserProfileManager class into this package.
  • Ensure the class and its necessary methods are accessible to the main app target (remember the access modifiers!).
  • The Challenge: The UserProfileManager currently relies on a UserSession singleton located in the main app. To avoid a circular dependency, create a SessionProvider protocol within the UserIdentity package. Update the UserProfileManager to use this protocol instead of the singleton, and implement the protocol in the main app to inject the actual session.
  • Verify that the main app can successfully initialize the UserProfileManager and fetch a profile.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.