Adding external libraries to iOS projects with the Swift Package Manager

by @ralfebert · updated November 03, 2021
Xcode 13 & iOS 15
Developers without prior iOS knowledge

The Swift Package Manager can be used to add external libraries in Xcode projects. This makes the tool a good alternative to Cocoapods and Carthage for managing the dependencies of an iOS project.

The following tutorial shows how to use the Swift Package Manager by adding the 3rd party library Kingfisher for asynchronous image loading to an example project. This library provides the metadata required for the Swift Package Manager, recognizable by the file Package.swift in the root folder of the project.

  1. Download the starter project for the sample project Countries. This contains the basic structure for an app that displays images using the SwiftUI List view:

  2. Open the Kingfisher project page and copy the clone URL of the project:

    Clone-URL von Kingfisher kopieren
  3. In Xcode use File » Swift Packages » Add Package Dependency… to add a new dependency:

    Xcode: Add Package Dependency
  4. Specify the clone URL of the Kingfisher library:

    File » Swift Packages » Add Package Dependency…
  5. Leave the default version settings - the library will be updated until the next major release:

    Xcode Package Options
  6. Add the Kingfisher target to the app target:

    Xcode Add Package
  7. The library will be set up in the project and appear in the Project Navigator:

    Xcode Swift Package Dependencies
  8. Have a look at Swift Packages in the project settings. Here, the package configuration can be changed later:

    Swift Packages im Xcode-Projekt
  9. Use the library in the CountryRowView: Import the Kingfisher module there and use the KFImage class to show the images downloaded from the URL from the data model:

    import SwiftUI
    import Kingfisher
    struct CountryRowView: View {
        let country: Country
        var body: some View {
            HStack {
                    .frame(width: 50)

Q & A

Where are the checked out modules stored?

In the Derived Data folder of Xcode:

What happens if the project is opened without the library having been downloaded?

The library will be automatically downloaded by Xcode:

What happens when a new version of the library is released?

The commit hash of the library is stored in the Xcode project under project.xcworkspace/xcshareddata/swiftpm/Package.resolved. This declaration is used to download the library. There is no automatic update, the version of the library will be fixed.

The dependency can be updated with File » Swift Packages » Update to Latest Package Versions.

More information