Creation and usage of a simple Swift package

suggest change

To create a Swift Package, open a Terminal then create an empty folder:

mkdir AwesomeProject
cd AwesomeProject

Initialize a Git repository:

git init

Then create the package itself. One could create the package structure manually but there’s a simple way using the CLI command.

If you want to make an executable:

swift package init --type executable

Several files will be generated. Among them, Sources/AwesomeProject/AwesomeProject.swift (a type marked @main; older versions generated main.swift) will be the entry point for your application.

If you want to make a library:

swift package init --type library

The generated AwesomeProject.swift file will be used as the main file for this library.

In both cases you can add other Swift files in the Sources folder (usual rules for access control apply).

The Package.swift file itself will be automatically populated with content like this (simplified; the tools version matches your Swift version):

// swift-tools-version:5.9
import PackageDescription

let package = Package(
    name: "AwesomeProject",
    targets: [
        .executableTarget(name: "AwesomeProject")
    ]
)

Versioning the package is done with Git tags:

git tag '1.0.0'

Once pushed to a remote or local Git repository, your package will be available to other projects.

Your package is now ready to be compiled:

swift build

The compiled project will be available in the .build/debug folder.

Your own package can also resolve dependencies to other packages. For example, if you want to include “SomeOtherPackage” in your own project, change your Package.swift file to include the dependency:

// swift-tools-version:5.9
import PackageDescription

let package = Package(
    name: "AwesomeProject",
    dependencies: [
        .package(url: "https://github.com/someUser/SomeOtherPackage.git", from: "1.0.0"),
    ],
    targets: [
        .executableTarget(
            name: "AwesomeProject",
            dependencies: [.product(name: "SomeOtherPackage", package: "SomeOtherPackage")]
        )
    ]
)

Then build your project again: the Swift Package Manager will automatically resolve, download and build the dependencies.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents