Skip to content
LumenaryAcademy
Foundations 45 min

First steps in Swift

Where Swift came from, what it is for, how to install it, and your first compiled programs.

Code tested · 4AI-draftedAwaiting review by a computer scientist
MotivationH

Why learn Swift?

Pick up an iPhone and open almost any app: a bank, a messaging app, a game, a map. There is a very good chance its code is written in Swift. Swift is the language Apple built for its own platforms, and it is how most new software for iPhone, iPad, Mac, Apple Watch, Apple TV and Apple Vision Pro is written today.

That alone would make it worth learning, but Swift is not only an Apple language. It is open source, it runs on Linux and Windows, and people use it for web servers, command-line tools, machine-learning experiments and even small embedded chips. Apple itself runs Swift on its servers. If you learn Swift you learn a modern, carefully designed language that will run nearly anywhere you need it.

Swift also teaches good habits. It was designed after decades of experience with C, C++ and Objective-C, by people who had watched the same bugs appear again and again: reading a variable before it was set, running off the end of an array, forgetting that a value might be missing, two threads writing the same memory at once. Swift turns many of those mistakes into compile-time errors, so the compiler tells you about them before your users do.

This first lesson sets you up. You will learn a little history, install the toolchain, compile and run your first programs, and make a small project with Swift Package Manager, the tool professionals use for every Swift project that is not an app built in Xcode.

History & global context

Where Swift came from

Swift began in 2010 as a personal project of Chris Lattner, an engineer at Apple who had earlier created LLVM, the compiler infrastructure that now sits underneath Clang, Rust, Swift and many other languages. Others at Apple joined, and Apple announced Swift to the world at its developer conference in June 2014. Until then Apple's platforms were programmed mainly in Objective-C, a language from the 1980s that adds objects to C. Swift was meant to keep everything Apple developers could already do, including calling all the existing Objective-C code, while removing C's sharp edges.

A few milestones explain the Swift you will meet today:

YearVersionWhat changed
20141.0First release, for iOS and macOS apps
20152.0Error handling with throws, try and catch; open-sourced in December under the Apache 2.0 licence, with Linux support
20163.0A large clean-up: API names were rewritten to follow the new API Design Guidelines
20195.0ABI stability: compiled Swift code from different compiler versions can work together, so the standard library ships inside Apple's operating systems
20215.5async/await, structured concurrency and actors
20235.9Macros, if and switch as expressions, and types that cannot be copied
20246.0The Swift 6 language mode, which proves your program free of data races at compile time; typed throws

Since 2015 every change to the language goes through Swift Evolution: someone writes a proposal (they are numbered, like SE-0413 for typed throws), it is discussed in public on the Swift Forums, and a steering group accepts, revises or rejects it. When this course says "since Swift 5.9", you can look up the proposal and read exactly why the feature exists. The project moved its code to the swiftlang organization on GitHub in 2024.

ExplanationH

Safe, fast and expressive

Swift's designers describe their goals in three words, and almost every feature you will meet in this course serves at least one of them.

Safe. The compiler refuses to let you read a variable before giving it a value. Arrays check every index, and integers check every arithmetic operation for overflow; when a check fails, the program stops on the spot (it traps) rather than carrying on with corrupted data. A value that might be missing has a different type (an optional) from one that cannot be, so you cannot forget to handle the missing case. Memory is managed automatically. In the Swift 6 language mode the compiler even checks that no two threads can touch the same mutable data at once.

Fast. Swift is compiled ahead of time, through LLVM, into native machine code. There is no virtual machine and no tracing garbage collector pausing your program. Its most common types (numbers, strings, arrays, dictionaries, and the structs you write) are value types that can live on the stack or inline in other values, and its generic code is specialized by the compiler for the types you actually use.

Expressive. You rarely write types that the compiler can work out for itself. Functions read like phrases at the call site: insert(item, at: 0). Closures, protocols and enums with attached data let you say a lot in a few lines without giving up on any of the checks above.

These goals pull against each other sometimes. A check costs a little time; a strict compiler can feel fussy. When they conflict, Swift usually picks safety first and then works hard to make the safe version fast. You will see this trade-off again and again.

ComputationC

Installing the toolchain

A Swift toolchain is the compiler (swiftc), the swift driver that runs packages, tests and scripts, the standard library, Foundation, the testing libraries and the package manager, all versioned together. Get it from swift.org/install:

  • macOS. Install Xcode from the App Store; it includes the toolchain. For command-line work without Xcode, swift.org offers swiftly, the official toolchain manager, which installs and switches between Swift versions.
  • Linux. Use swiftly as well; it supports the common distributions. Official Docker images named swift are another clean option.
  • Windows. swift.org has an installer, and package managers such as WinGet can install it too.

Then open a terminal and check what you have:

bash
swift --version

On the machine that checked this course it printed Swift version 6.4.2 (swift-6.4.2-RELEASE) followed by the target platform. Anything from 6.0 onwards will run every program in this course; a few features are marked with the version that introduced them.

You also need an editor. Xcode is the natural choice on a Mac. On any system, Visual Studio Code with the official Swift extension (published by the Swift project) gives you completion, errors as you type and a debugger, all powered by sourcekit-lsp, the language server that ships with the toolchain. Any editor that speaks the Language Server Protocol, such as Neovim or Zed, can use it too.

There is no official online playground for Swift. If you have an iPad or a Mac, Apple's free Swift Playgrounds app is a pleasant place to experiment; otherwise, a terminal and an editor are all you need.

Worked examplesH

Your first program

Make an empty folder, create a file called main.swift and type one line:

swift
print("Hello, world!")

Compile it and run the result:

bash
swiftc main.swift -o hello
./hello

It prints:

text
Hello, world!

Notice what is not there. There is no main function, no import, no semicolon, no class wrapping everything. A file named main.swift may contain top-level code: statements that run from top to bottom when the program starts. In every other file of a program, only declarations (functions, types, constants) are allowed at the top level. Semicolons are needed only to put two statements on one line, and Swift programmers almost never do that.

swiftc is the compiler. It turned your source into a native executable called hello, which you can copy to another machine with the same operating system and run without Swift installed (on Linux, the Swift runtime libraries must be present or linked statically). There is also a shortcut: swift main.swift compiles the file in memory and runs it immediately, which is handy for small scripts. For anything bigger than one file you will use a package, as you will see below.

A few more lines

Here is a program that uses a little of everything you will learn in the next lessons: a constant holding an array of pairs, a for loop that takes each pair apart, and string interpolation, which puts a value inside a string with \(...).

swift
let greetings = [
    ("Swahili", "Habari"),
    ("Japanese", "こんにちは"),
    ("Hindi", "नमस्ते"),
    ("Portuguese", "Olá"),
]

for (language, word) in greetings {
    print("\(language): \(word) has \(word.count) characters")
}
text
Swahili: Habari has 6 characters
Japanese: こんにちは has 5 characters
Hindi: नमस्ते has 3 characters
Portuguese: Olá has 3 characters

Look at the Hindi line. नमस्ते is stored as six Unicode code points, but Swift counts 3 characters, because it counts what a reader sees as single letters (the conjunct स्ते is one). Most languages would print 6 or even 18 (the number of bytes). Swift's String is Unicode-correct by default, and you will see in the next lesson what that costs and why it is worth it. Notice also the comma after the last pair: Swift allows a trailing comma in array literals, which keeps version-control diffs clean when you add a line.

Functions and a decision

swift
func fahrenheit(fromCelsius c: Double) -> Double {
    c * 9 / 5 + 32
}

let readings = [-10.0, 0.0, 21.5, 37.0, 100.0]

for c in readings {
    let f = fahrenheit(fromCelsius: c)
    print("\(c) °C is \(f) °F")
}

let hottest = readings.max() ?? 0
print("Hottest reading: \(hottest) °C")
text
-10.0 °C is 14.0 °F
0.0 °C is 32.0 °F
21.5 °C is 70.7 °F
37.0 °C is 98.6 °F
100.0 °C is 212.0 °F
Hottest reading: 100.0 °C

Three things to notice. The function has an argument label, fromCelsius, used by callers, and a parameter name, c, used inside; this is why the call reads fahrenheit(fromCelsius: c). Its body is a single expression, so return can be left out. And readings.max() does not return a Double but an optional Double, because an empty array has no maximum; ?? 0 says "or 0 if there is none". The compiler would not let you print the maximum without deciding what to do about the empty case. That is the safety goal at work, in the second program you ever wrote.

Worked examplesH

Safety you can see

What happens when an Int8 (an integer stored in 8 bits, so between −128 and 127) goes past its limit? In C the result is undefined behaviour: the compiler may assume it never happens, with surprising results. In Swift, plain + traps: the program stops with a crash report rather than producing a wrong number. When you really do want the wrap-around arithmetic of the hardware, for hashing or checksums, you ask for it by name:

swift
let a: Int8 = 120
let b: Int8 = 10
let (sum, overflowed) = a.addingReportingOverflow(b)
print("120 + 10 as Int8 is \(sum), overflowed: \(overflowed)")
print("With &+ it wraps silently: \(a &+ b)")
text
120 + 10 as Int8 is -126, overflowed: true
With &+ it wraps silently: -126

The &+ operator (and &-, &*) wraps. addingReportingOverflow returns a tuple, a pair of values, which the let (sum, overflowed) line takes apart. The unsafe behaviour exists, but you have to type an extra character to get it, so a reader can see where it happens.

ComputationC

Packages: how real Swift projects are organized

Single files are fine for learning, but every real Swift project outside Xcode's app templates is a package, managed by Swift Package Manager (SwiftPM), which is part of the toolchain. A package has a manifest, Package.swift, written in Swift itself, that names its targets (modules of code), its products (what it builds, such as an executable or a library), and its dependencies on other packages, which SwiftPM downloads from Git repositories.

Try it:

bash
mkdir Greeter && cd Greeter
swift package init --type executable
swift run

With Swift 6.4, init created this layout:

text
Greeter/
├── Package.swift
├── Sources/
│   └── Greeter/
│       └── Greeter.swift
└── Tests/
    └── GreeterTests/
        └── GreeterTests.swift

swift run builds the package (into a hidden .build folder) and runs it, printing Hello, world!. The generated source does not use top-level code. Instead it marks a type with @main, and the program starts in that type's static func main():

swift
@main
struct Greeter {
    static func main() {
        print("Hello, world!")
    }
}

The manifest begins with a special comment, // swift-tools-version: 6.4, which states the oldest toolchain that can build the package and, just as importantly, the language mode: a package whose tools version is 6.0 or later is compiled in the Swift 6 language mode, with full data-race checking. A single file compiled with plain swiftc, as in this course's checked examples, still defaults to the Swift 5 mode, where those checks are warnings; add -swift-version 6 to get the strict behaviour. Every program in this course compiles cleanly in both modes.

The other commands you will use every day:

CommandWhat it does
swift buildcompile (debug by default; -c release for an optimized build)
swift runbuild and run an executable target
swift testbuild and run the tests in Tests/
swift package add-dependency <url>add a package dependency to the manifest
swift formatformat the source (bundled with the toolchain since Swift 6)

The test file that init generated uses Swift Testing, the modern testing library that ships with the toolchain; you will write real tests with it in Errors and testing. Dependencies are found on the community-run Swift Package Index.

Common misconceptionsH

Common misconceptions

Misconception

"Swift only runs on Apple devices." Swift is open source and has official toolchains for Linux and Windows. What is Apple-only are some frameworks: SwiftUI, UIKit and AppKit belong to Apple's operating systems. The language, its standard library, Foundation, Swift Testing and SwiftPM are cross-platform, which is why every program in this course runs on Linux.

Misconception

"Swift is a scripting language because swift file.swift runs a file directly." That command compiles the file in memory and then runs the machine code. Swift is always compiled; the shortcut just hides the step. For production you build a binary, usually with swift build -c release, and the optimizer can make that build many times faster than the debug build.

Misconception

"A crash on overflow is worse than C's behaviour." It feels harsh, but a program that stops at the first wrong number is far easier to debug, and far safer, than one that carries on with a corrupted balance or a negative array index. When wrapping is really what you mean, &+ is one character away.

ExplanationH

How professionals work

Day to day, a Swift developer building apps lives in Xcode, which wraps the same toolchain in an editor, a visual interface designer, simulators for every Apple device, and profiling tools called Instruments. A developer building servers or tools works with SwiftPM in a terminal and an editor such as VS Code. Both kinds follow the same conventions: types are UpperCamelCase, everything else is lowerCamelCase, indentation is four spaces, and names are chosen so that call sites read clearly, as described in the official API Design Guidelines. Reading those guidelines once, early, is one of the best investments you can make in writing Swift that other Swift programmers find natural.

They also keep up with the language. Swift changes every year (a release usually arrives each spring and each autumn), and the Swift blog and the Evolution dashboard say what each release brings. You do not need to chase every feature, but knowing they exist helps you read other people's code.

Exercises

Exercises

1. First steps in Swift

Warm-upHuman

A program has three files: main.swift, Money.swift and Report.swift. In which of them may you write a statement such as print("Starting") directly at the top level, outside any function or type?

Choose one

2. First steps in Swift

Warm-upComputational

What does this program print? Type the line exactly.

let words = ["sun", "moon", "star"]
var total = 0
for w in words {
    total += w.count
}
print("\(words.count) words, \(total) letters")

3. First steps in Swift

CoreComputational

UInt8 holds whole numbers from 0 to 255. What does this program print?

let x: UInt8 = 250
print(x &+ 10)

4. First steps in Swift

CoreComputational

In UTF-8, ó takes 2 bytes and every other letter of this city's name takes 1. What does the program print?

let city = "Kraków"
print(city.count, city.utf8.count)

5. First steps in Swift

CoreHuman

A package's Package.swift starts with // swift-tools-version: 6.0. What does that line do?

Choose one

6. First steps in Swift

CoreHuman

Which of these can you use in a Swift program on Linux? List every one that applies, by letter (for example A, C).

  • A. The standard library (Array, String, print)
  • B. SwiftUI
  • C. Swift Package Manager
  • D. Foundation (Date, JSONEncoder)
  • E. UIKit
  • F. Swift Testing

Write elements separated by commas. Order and repeats don’t matter — just like in a set!

7. First steps in Swift

Warm-upHuman

You are inside the folder of a package with an executable target. Which command builds the package and then runs the executable? Type the whole command.

Further reading and resources