Back in December I opened an enhancement request in the Swift JIRA site, issue SR-353, to add an
npm init-style invocation to
swift build for creating all of the boilerplate files needed for a complete Swift package. It wasn’t too long after the request was added that Bastian Rinsche and Tobias Landsberg implemented the feature and had a pull request accepted. Bastian has written up a great post on his experience with opensource Swift and contributing to the community with the implementation of
swift build --init.
Let’s look at how it works. First, create a new directory with
mkdir for your package or application. We’ll use
helloworld as an example:
mkdir helloworld. Now,
cd into your
helloworld directory and run
swift build --init.
# cd helloworld # swift build --init Creating Package.swift Creating .gitignore Creating Sources/ Creating Sources/main.swift Creating Tests/
Let’s take a look at what
swift build --init generates:
Package.swift– the “manifest” for this package;
swift build --initnames your package the same as the directory you invoked it in
Sources– SwiftPM convention is that source files are included in a directory called
main.swift– Swift applications will have one (and only one)
main.swiftfile as the execution entry point
Tests– a directory to hold testcases for the application; more on this in a moment
.gitignore– a handy Git gitignore starter file that ignores build artifacts such as
Packages(things you don’t want to check in to a repository)
Package.swift looks like this:
let package = Package(
swift build at this point will create
.build/debug/helloworld which when executed you will see
If you are building a Swift-based library then remove
main.swift and replace it with your library code. Without a
main.swift SwiftPM will create a static library archive.
Getting the Ubuntu Package
To get started with
swift build --init you can grab the latest Ubuntu package for Swift 2.2 (as of this writing, version 2.2-0ubuntu15). See this post for instructions. For more details about using SwiftPM in general, see our introduction here. Happy Swifting!