Swift Package Manager (SPM) is a powerful tool for modularizing your code and managing dependencies in your projects. If you’re working on a project that uses SPM for modularization, you may need to add internal dependencies to connect different parts of your codebase. In this article, we’ll go over how to add internal dependencies in SPM and configure your Package.swift file to properly connect them.

Assumptions

Before we get started, let’s make a few assumptions about your project and its structure:

  • You’re working on a project where modularization is done using SPM.
  • You have an SPM package that depends on other packages.

Here’s how my project structure looks like:

Project structure

Connecting Internal Dependencies

To connect the internal dependencies in your Package.swift file, you need to specify the dependencies for your package and the dependencies for your targets. Here’s an example Package.swift file that configures the FeatureModules package with its internal dependencies:

// swift-tools-version: 5.7
// The swift-tools-version declares the minimum version of Swift required to build this package.

import PackageDescription

let package = Package(
    name: "FeatureModules",
    platforms: [.iOS(.v16), .macOS(.v13)],
    products: [
        .library(
            name: "FeatureModules",
            targets: ["Dashboard"]),
    ],
    dependencies: [
        // Dependencies declare other packages that this package depends on.
        // .package(url: /* package url */, from: "1.0.0"),
        .package(path: "../DomainModels"),
        .package(path: "../Resources"),
        .package(path: "../Shared"),
        .package(path: "../Storage"),
    ],
    targets: [
        .target(
            name: "Dashboard",
            dependencies: [
                .product(name: "DomainModels", package: "DomainModels"),
                .product(name: "Resources", package: "Resources"),
                .product(name: "Shared", package: "Shared"),
            ]),
        .testTarget(
            name: "DashboardTests",
            dependencies: [
                "Dashboard",
                .product(name: "Storage", package: "Storage"),
          ]),
    ]
)

Conclusion

Connecting internal dependencies in Swift Package Manager is a crucial step when working on modularized projects. By properly configuring the Package.swift file and specifying the dependencies, you can ensure that your code compiles and runs without any issues. Remember to use the .product declaration when specifying dependencies in your target, and to make sure that the package paths are correctly set in the Package.swift file. By following these steps, you can maintain a well-organized project structure and increase code reusability across your codebase.

Resources