Running and Compiling Swift Code in Terminal

Sometimes its more convenient to run swift code in terminal. Specially when I implement data structure or test any algorithm, I like to write code in a text editor and run in terminal. Lets see how we can do it in macOS terminal:

1. How to check swift version

swift --version

it shows the following output in my terminal

Image for post
Image for post

2. Writing a simple swift code and run in terminal

test.swift

print("Hello World")

Run in terminal

swift test.swift

output

Hello World

3. Compiling swift code to executable file

If we want to compile 2 or more swift files together, we must have a file named main.swift which is the top level executable file. Its like main function in C or C++ or Java.

file1: a.swift

func helloWorld(){
print("Hello World")
}

file2: main.swift

func hello(){
helloWorld()
}

hello()

To compile and create an executable program:

swiftc a.swift main.swift -o prog

It will compile both a.swift and main.swift files linked together and create an executable file named prog.

To run the executable program in terminal:

./prog

output

Hello World

source: thinkdiff.net

Written by

Programmer | Writer | Traveller → https://thinkdiff.net

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store