how to create multiple swift packages and add them as dependency on another package

Asked on 07/31/2024

1 search

To create multiple Swift packages and add them as dependencies on another package, you can follow these steps:

  1. Create Swift Packages:

    • Use the Swift Package Manager (SPM) to create your packages. You can do this from the command line:
      swift package init --type library
      
    • This command will create a new Swift package with a library target.
  2. Define Dependencies:

    • In each package, you can define dependencies in the Package.swift file. For example:
      // swift-tools-version:5.5
      import PackageDescription
      
      let package = Package(
          name: "MyLibrary",
          products: [
              .library(
                  name: "MyLibrary",
                  targets: ["MyLibrary"]),
          ],
          dependencies: [
              // Dependencies declare other packages that this package depends on.
              .package(url: "https://github.com/another/package.git", from: "1.0.0"),
          ],
          targets: [
              .target(
                  name: "MyLibrary",
                  dependencies: []),
              .testTarget(
                  name: "MyLibraryTests",
                  dependencies: ["MyLibrary"]),
          ]
      )
      
  3. Add Dependencies to Another Package:

    • To add these packages as dependencies to another package, you need to update the Package.swift file of the main package:
      // swift-tools-version:5.5
      import PackageDescription
      
      let package = Package(
          name: "MainPackage",
          products: [
              .executable(
                  name: "MainPackage",
                  targets: ["MainPackage"]),
          ],
          dependencies: [
              .package(path: "../MyLibrary1"),
              .package(path: "../MyLibrary2"),
          ],
          targets: [
              .target(
                  name: "MainPackage",
                  dependencies: ["MyLibrary1", "MyLibrary2"]),
          ]
      )
      
  4. Build and Test:

    • You can build and test your packages using the command line:
      swift build
      swift test
      

For more detailed information on working with Swift packages, you can refer to the session A Swift Tour: Explore Swift’s features and design which covers code organization and the use of Swift Package Manager.

Relevant Sessions

These sessions provide insights into creating and managing Swift packages, as well as using them in different environments.