Hello World in Swift
Your first Swift program - the classic Hello World example with Docker setup
Every programming journey starts with Hello World. Let’s write our first Swift program.
The Code
Create a file named hello.swift:
| |
That’s it! Swift’s clean syntax means Hello World is just a single line.
Understanding the Code
print()- A global function that outputs text to the console"Hello, World!"- A String literal enclosed in double quotes- No semicolon - Swift doesn’t require semicolons at the end of statements
- No main function - Top-level code runs automatically in Swift scripts
Running with Docker
The easiest way to run this without installing Swift locally:
| |
Running Locally
If you have Swift installed (comes with Xcode on macOS):
| |
Expected Output
Hello, World!
Key Concepts
- Swift is concise - No boilerplate required for simple programs
- Scripts vs Applications -
.swiftfiles can run directly or be compiled - Type inference - Swift figures out types automatically
- Modern syntax - Clean, readable code without unnecessary ceremony
A More Detailed Version
For a slightly more structured approach:
| |
This version demonstrates:
import Foundation- Swift’s core library (not needed for basic print)- Function definition - Using
funcwith named parameters - String interpolation - Embedding values with
\() - Constants - Using
letfor immutable values - Type annotations - Explicit
Stringtypes (optional due to inference)
Why Swift Stands Out
Coming from other languages, you’ll notice Swift’s unique characteristics:
- No header files - Everything in one
.swiftfile - Named parameters -
greet(name: "World")is self-documenting - Optionals - Built-in null safety (we’ll cover this later)
- Protocol-oriented - Composition over inheritance
Next Steps
Continue to Variables and Data Types to learn about Swift’s powerful type system, including optionals, value types, and type inference.
Running Today
Last updated: