Running and Compiling Swift Code in Terminal

Mahmud Ahsan
1 min readJun 20, 2018

--

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

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

--

--

Mahmud Ahsan
Mahmud Ahsan

Written by Mahmud Ahsan

I'm a software engineer passionate about web and mobile app development.

No responses yet