Beginner

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:

1
print("Hello, World!")

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:

1
2
3
4
5
# Pull the official Swift image
docker pull swift:6.0

# Run the program
docker run --rm -v $(pwd):/app -w /app swift:6.0 swift hello.swift

Running Locally

If you have Swift installed (comes with Xcode on macOS):

1
2
3
4
5
6
# Run directly as a script
swift hello.swift

# Or compile and run
swiftc hello.swift -o hello
./hello

Expected Output

Hello, World!

Key Concepts

  1. Swift is concise - No boilerplate required for simple programs
  2. Scripts vs Applications - .swift files can run directly or be compiled
  3. Type inference - Swift figures out types automatically
  4. Modern syntax - Clean, readable code without unnecessary ceremony

A More Detailed Version

For a slightly more structured approach:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
import Foundation

// A proper greeting function
func greet(name: String) -> String {
    return "Hello, \(name)!"
}

// Call the function
let message = greet(name: "World")
print(message)

This version demonstrates:

  • import Foundation - Swift’s core library (not needed for basic print)
  • Function definition - Using func with named parameters
  • String interpolation - Embedding values with \()
  • Constants - Using let for immutable values
  • Type annotations - Explicit String types (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 .swift file
  • 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

All examples can be run using Docker:

docker pull swift:6.0
Last updated: