Your First Swift Program
In this page:
The Classic Hello World
The traditional first program in any language prints a greeting to the screen. In Swift, this takes just one line thanks to the built-in print function, with no imports or boilerplate required for a simple script.
Example: The Classic Hello World
print("Hello, World!")
Login to try C/C++/Java/PHP code in the editor
Running the Program
A Swift file is executed by passing it to the swift command, which compiles and immediately runs it in one step, printing any output to the terminal.
Example: Running the Program
swift hello.swift
⚠️ Run this command in your terminal.
Adding More Statements
A Swift program is simply a sequence of statements executed from top to bottom. You can add more print calls, and each one produces its own line of output when the program runs.
Example: Adding More Statements
print("Hello, World!")
print("Welcome to Swift")
print("This is my first program")
Login to try C/C++/Java/PHP code in the editor
- Forgetting that Swift statements don't need a
mainfunction or class wrapper -- top-level code in a single file just runs directly. - Misnaming the file extension (e.g.
.txtinstead of.swift), which prevents theswiftcommand from recognizing it. - Expecting output in a popup window instead of the terminal when running a command-line Swift script.
- A minimal Swift program can be a single line:
print("Hello, World!"). - Swift files use the
.swiftextension and are run withswift filename.swiftor compiled withswiftc. - Top-level code in
main.swift(or a single-file script) executes directly, no wrapper class needed. - This simplicity is one reason Swift is approachable for beginners.
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: