Creating a library package

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:

As we are getting started with SPM, the command we are the most interested in is swift package init.

Swift Package Manager is designed to build command-line tools and libraries for Linux and macOS targets. You will not be able to depend on Apple's proprietary frameworks, such as UIKit. Note that swift web apps (Kitura- or Vapor-based) are a perfect scenario to use SPM.

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

If your OS does not have the tree command available, you can use find . -not -path '*/\.*', which provides equivalent information. Alternatively, if you have Homebrew or MacPorts available, you can easily install by executing brew install tree or port install tree.

Swift Package manager created the directory structure and files for us. Here are some are notable ones:

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.