Hands-On Full:Stack Development with Swift
上QQ阅读APP看书,第一时间看更新

Getting started with Swift package manager

Mastering the command line is important, especially when trying to build and deploy Swift on a production Linux machine or in the Cloud. Since Xcode will not be available on those hosts, Apple has provided us with an easy-to-use command-line tool to help create, build, and distribute our Swift code. This tool is called the Swift package manager and it is useful for managing the distribution of Swift code while integrating with the Swift build system to automate the process of downloading, compiling, and linking dependencies. The following are some of the useful commands provided by the package manager to quickly get you started:

  • swift package init: This will create a Swift package or module that is an easy portable way to share code. It will create a package using the name of the folder you are currently in. Passing a --type executable option will make an executable package where the product of the build will be an executable program such as a web server or a command-line program. Think of this as gems for Ruby or node modules for Node.js.
  • swift build: This builds the Swift package you currently are in by compiling Swift code in your Sources folder. If your package is an executable, then it will generate a binary in the .build/debug folder. If you pass a release configuration using the --configuration release option, then it will build a highly optimized binary and place it in .build/release. The same output is generated for non-executable binary but generate Swift modules instead to be imported by whoever wants to use this module.
  • swift run: A quick way to run a Swift executable package from the command line. This command builds the Swift code if it is not built already and runs the binary. You can pass the -c release option to build and run the optimized version of the binary.
  • swift test: To run tests written in the Test folder of your package.
  • swift package generate-xcodeproj: This command generates an Xcode project file so that you can work on the package in Xcode instead of a plain text editor.

These are some of the more important commands that will come in handy when trying to build and test your web server in Swift and also when deploying and running your web application in production. There are a lot more commands and you can learn about them by running swift package in the Terminal: