In order to create a package, you will use the swift package command.
Running the command without any argument will print in the terminal the different options and subcommands you can run. As we are getting started, here are the most important ones:
- swift package init: Initializes a new package.
- swift package update: Updates package dependencies.
- swift package generate-xcodeproj: Generates an Xcode project.
- swift package describe: Describes the current package.
As we are getting started with SPM, the command we are the most interested in is swift package init.
For the example, we'll recreate a popular HTTP client library, inspired by the popular node.js request library.
As the library's goal is to be able to call URLs, and will be similar to cURL, let's call it swURL:
$ mkdir swURL # create the swURL folder
$ cd swURL
$ swift package init --type library # create the library in the current folder
Creating library package: swURL
Creating Package.swift
Creating README.md
Creating .gitignore
Creating Sources/
Creating Sources/swURL/swURL.swift
Creating Tests/
Creating Tests/LinuxMain.swift
Creating Tests/swURLTests/
Creating Tests/swURLTests/swURLTests.swift
Creating Tests/swURLTests/XCTestManifests.swift
$ tree
.
├── Package.swift // 1
├── README.md
├── Sources
│ └── swURL // 2
│ └── swURL.swift
└── Tests
├── LinuxMain.swift // 3
└── swURLTests
├── XCTestManifests.swift
└── swURLTests.swift
Swift Package manager created the directory structure and files for us. Here are some are notable ones:
- Package.swift: This is the package manifest.
- The swURL folder in sources: This is the main folder in which we'll put the sources for our library.
- LinuxMain.swift: This is required to run the tests on Linux.
Without any modifications to the current sources, we can build and test the project:
$ swift build
Compile Swift Module 'swURL' (1 sources)
$ swift test
Compile Swift Module 'swURLTests' (2 sources)
Linking ./.build/x86_64-apple-macosx10.10/debug/swURLPackageTests.xctest/Contents/MacOS/swURLPackageTests
Test Suite 'All tests' started.
Test Suite 'swURLPackageTests.xctest' started
Test Suite 'swURLTests' started.
Test Case '-[swURLTests.swURLTests testExample]' started.
Test Case '-[swURLTests.swURLTests testExample]' passed (0.160 seconds).
Test Suite 'swURLTests' passed.
Executed 1 test, with 0 failures (0 unexpected) in 0.160 (0.160) seconds
Test Suite 'swURLPackageTests.xctest' passed.
Executed 1 test, with 0 failures (0 unexpected) in 0.160 (0.160) seconds
Test Suite 'All tests' passed.
Executed 1 test, with 0 failures (0 unexpected) in 0.160 (0.160) seconds
Now you are all set up, and your new library is ready to be actively developed.