When we run our code using the swift command, or the Swift REPL tool, we are running the code as we would run a typical interpreted script such as a Bourne Again SHell (BASH) or Python script. This is really nice if we want to use Swift as a scripting language but if we want to build applications with Swift, we will need to compile our code into an executable form. To do this, we can use the Swift compiler.
Let's see how we would use the Swift compiler to build the Hello World example that we created earlier. If you recall from that example, we had to create a main.swift
file. While using a main.swift
file is not required for an application that only contains a single source file, it is required for applications that contain multiple source files. The Swift compiler will look for the main.swift
and use it as the entry point for the application, similar to how a C compiler uses the main()
function.
To build the Hello World application that we created earlier, we would need to run the following command in the same directory that the main.swift
file is in:
swiftc main.swift
This command should only take a second or so to run. Once it is completed, we should have an executable file named main
. If your application contains multiple files, you can list them one by one as follows:
swiftc main.swift file1.swift file2.swift file3.swift
If you want to change the name of the output file, you can use the -o
option as follows:
swiftc main.swift file1.swift file2.swift -o myexecutable
There are a number of command line options that you can use with the swift compiler. However, if you find that you are using a lot of command line options and making a complex compiler statement, you may want to look at the Swift Package Manager.