How to Create and Publish Your Own Swift Package Manager (SPM) Library

Vitaliy Podolskiy
2 min readJul 25, 2023

--

Swift Package Manager is a tool for automatically downloading, compiling, and linking your project’s dependencies. In this article, we will look at how to create and publish your own library using SPM.

Creating a Package

1 Create a new folder for your package: mkdir MyPackage && cd MyPackage.

2 Run the command swift package init --type library. This will create a new package with a set of standard files and folders.

3 Open the Package.swift file in a text editor. This file describes the structure of your package and its dependencies. In the simplest case, it looks something like this:

import PackageDescription

let package = Package(
name: "MyPackage",
products: [
.library(
name: "MyPackage",
targets: ["MyPackage"]),
],
targets: [
.target(
name: "MyPackage",
dependencies: []),
.testTarget(
name: "MyPackageTests",
dependencies: ["MyPackage"]),
]
)

4 Add the code of your library in the Sources/MyPackage folder. For instance, you can create a file Sources/MyPackage/MyLibrary.swift with the following content:

5 Check that everything works by running the tests with the swift test command.

Publishing the Package

1 First, you need to push your package to a repository. If you’re using Git, you can do this as follows:

public struct MyLibrary {
public init() {}

public func helloWorld() {
print("Hello, World!")
}
}

2 Then, create a new repository on GitHub and link it to your local repository:

git remote add origin https://github.com/yourusername/MyPackage.git
git push -u origin master

3 Now your package is available for connection via Swift Package Manager. In Xcode, you can add it by selecting “File” > “Swift Packages” > “Add Package Dependency” and specifying the URL of your repository on GitHub.

Congratulations, you’ve just created and published your first Swift Package Manager package! This basic example can be extended by adding external dependencies to the package, multiple modules, etc. Don’t forget to describe the functionality of your package in detail in the README file, this will help other developers understand what your package does and how to use it.

Follow our news!

Best regards,
Vitaliy

--

--

Vitaliy Podolskiy

I have been developing applications for many years. More than 40 completed commercial projects.