Better Programming

Advice for programmers.

Follow publication

Member-only story

10 Tips to Run Swift From Your Terminal

Eric Yang
Better Programming
Published in
8 min readNov 3, 2020

Generic stock photo of code on a laptop screen
Photo by Ilya Pavlov on Unsplash

Sometimes when writing a block of Swift code, I don't bother to launch Xcode. Running the Swift commands swift and swiftc from the terminal are more lightweight and convenient. To debug and set a breakpoint, lldb does the job.

1. ‘swift’ Command to Get the Swift Version

After installing the latest version of Swift from the download page, I’ll run the command to verify I’m running the expected Swift version:

$ swift --version
What it looks like from the terminal to run the $ swift — version command
Swift version
  • It shows I’m currently on Swift 5.3
  • The Swift/Objective-C compiler is on version 12
  • The Swift environment is MacOS Catalina on a 64 bit CPU

2. Swift Command to Run the Swift File

Let’s using the vi editor to write our first Swift file Foo.swift to print out “Hello world!”:

$ vi Foo.swift

Write down the foo() function, and execute it:

Writing down the foo() function and executing it
‘Foo.swift’

To run the file, we use:

$ swift Foo.swift
Running the Swift file in the terminal
Run Swift file

3. Run the Swift File With Parameters

The CommandLine enumeration is part of the Swift standard library to provide the command line arguments. We use CommandLine.arguments to get the parameters after the swift command.

To print out the “Hello, Foo!” message, the code is:

Running Foo.swift with arguments
‘Foo.swift’ with arguments

To run the file with arguments, we use:

$ swift Foo.swift Foo

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

Eric Yang
Eric Yang

Written by Eric Yang

Senior iOS engineer🚀, double degrees with Computer Science⚡Content writer? Why not!🚀

Responses (3)

Write a response

Thank you for this!
You can always remove the (base) by typing "Conda deactivate" :)

Thank you, pretty strightforward tutorial.

Pretty nice! The only one missing is the simple case where you have file.swift and you want it to be compiled when executed by adding the shebang on the first line:
% cat foo.swift
#!/usr/bin/xcrun swift
func printHello() {
print("Hello, Swift!")
}...