Getting Started with Swift Package Manager (SPM)

Swift Package Manager (SPM) is a powerful tool provided by Apple for managing dependencies in Swift projects. It simplifies the process of integrating third-party libraries and frameworks into your projects, ensuring a smooth development experience. Prior to SPM, I had used cocoapodswhich is still indeed an active project, but with native support either Xcode baked in, I find it a much smoother and natural experience working with SPM.

In this tutorial, you will learn how to use Swift Package Manager to add and manage dependencies in your Swift projects.

Step 1: Creating a Swift Package

  1. Open Terminal.
  2. Navigate to the directory where you want to create your Swift package.
  3. Run the following command to create a new Swift package: .
swift package init

This command will generate the basic structure for a Swift package, including the `Sources` and `Tests` directories.

Step 2: Adding Dependencies

  1. Open the Package.swift file in a text editor or Xcode.
  2. Inside the `dependencies` array, add a new item for each dependency you want to include. For example:
dependencies: [ package(
url: “”, from: “5.4.0"), ]

This example adds the Alamofire library as a dependency to your project. Adjust the URL and version requirements based on your desired library.

Step 3: Resolving and Fetching Dependencies

  1. In Terminal, navigate to your project’s root directory.
  2. Run the following command to fetch and resolve the dependencies:
swift package resolve

SPM will analyze the package manifest and fetch the required dependencies from the specified sources.

Once the dependencies are resolved, you will find a new file named `Package.resolved` that lists the resolved versions of the dependencies.

Step 4: Using Dependencies in Your Code

  1. Open the Swift file where you want to use the added dependency.
  2. 2. Import the module using the `import` statement. For example, to import Alamofire:
import Alamofire

You can now use the features and functions provided by the imported dependency in your code.

Leave a Reply

Your email address will not be published. Required fields are marked *