Skip to content
Tutorials Center
My learning

Topics

Lesson 3 of 146 ยท Getting Started

How Swift Works

See how Swift source becomes a running program - the compiler pipeline, static typing, ARC memory management, value types, Foundation and SwiftPM.

You can write Swift for years without thinking about the machinery underneath, but a rough mental model pays off quickly. It explains why the compiler complains so much, why Swift programs start fast and use little memory, why struct and class behave differently and what the strange words "ARC", "LLVM" and "SwiftPM" mean. This lesson walks through the journey of a program, from text to running code, and then through the three promises that Swift makes at run time.

From source to machine code

Swift is a compiled language. A program called the compiler reads your text and produces an executable file made of machine instructions for one CPU family, so the CPU runs it directly. There is no interpreter and no virtual machine in between. The stages are:

  1. Parsing. The text is turned into a tree of declarations and expressions. Syntax errors, such as a missing brace, are reported here.
  2. Type checking and semantic analysis. The compiler works out the type of every expression, resolves names, checks that protocols are satisfied, checks access control, checks that every switch is exhaustive and that every variable is initialized before use. Most error messages you will see come from this stage.
  3. SIL generation and analysis. The checked program is turned into the Swift Intermediate Language, a representation that still understands Swift concepts such as optionals and reference counting. The compiler runs further safety passes here (for example, proving that a function with a return type returns on every path, and checking ownership and exclusive access rules) and performs Swift-specific optimizations.
  4. LLVM IR and code generation. SIL is lowered to LLVM's intermediate representation. LLVM, a compiler toolkit shared with C, C++, Rust and others, optimizes it further and emits machine code for the target (x86-64, ARM64 and more).
  5. Linking. The generated code is combined with the Swift runtime and the standard library into an executable.

You rarely see these stages, but their names show up in diagnostics. A message that mentions "SIL" or "LLVM" usually points to a compiler bug rather than your mistake.

Static typing: most mistakes never run

The first promise is that types are checked before the program runs. Every value has one type that the compiler knows. Calls with the wrong argument types, missing enum cases and misspelled names are all compile errors.

Swift Calling a function with the wrong type (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

You get an error whose first line is cannot convert value of type 'String' to expected argument type 'Double'. Nothing was compiled, and no test was needed to find the bug. Swift's inference is strong enough that you rarely write types for local variables, but the checking is still full strength: inference is not "dynamic typing".

Memory: ARC instead of a garbage collector

Programs create values all the time and must give the memory back. There are three common strategies: you free it yourself (C), a tracing garbage collector finds unused objects in the background (Java, C#, Go), or the compiler inserts the bookkeeping for you. Swift uses the third approach, called automatic reference counting (ARC).

Each class instance carries a counter of how many references point to it. The compiler inserts increments and decrements at the right places. When the counter reaches zero, the object is destroyed immediately, and its deinit runs. That makes object lifetimes deterministic: you can predict when cleanup happens, which is useful for files, locks and connections.

Swift Watching ARC destroy an object

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

A is not closed when first becomes nil, because second still points to it; it closes the moment second is set to nil too. B is closed at the end of the do block, where its only reference goes out of scope. Look at the output order: it is exactly what you can read from the code, with no randomness.

ARC has one famous weakness: reference cycles. If two objects point to each other with ordinary (strong) references, their counts never reach zero and they leak. Swift gives you weak and unowned references to break cycles; Deinitialization and ARC covers this in detail. Value types such as structs and enums do not use reference counting for themselves, and ARC overhead disappears for them.

ARC is not free: the counter updates cost a few instructions, and they are atomic so that threads can share objects safely. The optimizer removes many of them, and Swift's newer ownership features (borrowing, consuming, noncopyable types) let you avoid the rest in performance-critical code.

Value types, reference types and copy-on-write

The second promise is about what assignment means. Swift has two families:

  • Value types: struct, enum and tuples. Assigning or passing one makes a logically independent copy.
  • Reference types: class and closures. Assigning copies a reference to the same object.

The standard library collections (Array, Dictionary, Set, String) are structs. They would be slow if they copied all the elements on every assignment, so they use copy-on-write: the copies share one buffer until one of them is modified, and only then is the buffer duplicated.

Swift Arrays behave like values

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

You get value semantics, the safety of independent copies, without paying for copies you do not need. This is why Swift programmers can pass arrays to functions freely. Value vs Reference returns to the subject.

Runtime checks: safe by default, trap on misuse

The third promise is that when a safety check cannot be done at compile time, Swift performs it at run time and stops the program instead of corrupting memory. That stop is called a trap. You see traps for out-of-range array access, integer overflow, force-unwrapping nil and a failed precondition.

Swift Integer overflow traps (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Int8 holds -128 to 127, so 127 + 1 does not fit. In C the answer would silently wrap around. In Swift the program stops immediately. Our runner compiles with optimizations (-O), so you do not get a friendly message: the process dies with an illegal-instruction signal (Signal 4, SIGILL) and the runner prints a backtrace, with a note about the nonzero exit. In a debug build, such as a plain swift run, the trap also prints a short "Fatal error" message naming the problem. The Int8("1")! trick is only there so that the compiler cannot see the problem and reject it earlier; with plain literals you would get a compile-time error instead.

A trap is not an exception you catch. It is the language saying "this program has a bug". For expected failures such as bad user input, use optionals and throws (Optionals, Errors). If you really want wrapping behavior, there are explicit operators (&+) covered in Working with Numbers.

The standard library and Foundation

Two layers of library come with every Swift toolchain:

  • The Swift standard library is always available with no import. It defines Int, String, Array, Dictionary, Optional, Result, the collection and numeric protocols, print, concurrency basics, and more. It is written in Swift and compiled together with your program.
  • Foundation is a broader library for dates, calendars, files, URLs, JSON, number and date formatting and more. You add it with import Foundation. On Apple platforms it is part of the OS; on Linux and Windows it ships with the toolchain (as swift-foundation plus swift-corelibs-foundation).
Swift Standard library versus Foundation

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

sorted() and uppercased() are standard library. String(format:), replacingOccurrences(of:with:) and Date need import Foundation. If you forget the import you get cannot find 'Date' in scope. The runner also offers other modules such as Synchronization, RegexBuilder and Observation, which later lessons introduce. Apple-only frameworks (SwiftUI, UIKit, Combine, CoreData) do not exist here.

Modules and the Swift Package Manager

Swift code is organized into modules. Your program is one module; the standard library is another (Swift); import Foundation brings in a third. A package is a folder with a Package.swift file that describes modules, executables, tests and dependencies, built with the Swift Package Manager (SwiftPM). Read-only illustration:

Swift
// swift-tools-version: 6.0
import PackageDescription

let package = Package(
    name: "Greeter",
    targets: [
        .executableTarget(name: "Greeter")
    ]
)

On a real machine, swift build compiles it, swift run runs it and swift test runs its tests. SwiftPM and Xcode are not available in this course's runner, so every example is a single main.swift. Swift Package Manager explains packages and dependencies, and Swift on Apple Platforms covers Xcode.

Concurrency checking in Swift 6

Because our runner compiles in Swift 6 language mode, the compiler also verifies that concurrent code cannot have data races: two threads touching the same mutable data without protection. This is one more compile-time promise, built on Sendable types and actors. It starts to matter in the Concurrency chapter. For now, remember that in Swift 6 a global var shared between tasks is an error, not a warning.

Putting the model together

When you press Run: the server writes your code to main.swift, the compiler checks types and safety, generates and optimizes code, links it with the runtime and standard library, runs the executable and returns its output. Compile errors stop at step one. Runtime traps stop at the failing line. Everything else is the normal life of a program.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which technology does Swift use to manage the memory of class instances?

    The compiler inserts reference count updates; an object is destroyed as soon as its count reaches zero.
  2. 2. When does an object's deinit run under ARC?

    Lifetimes are deterministic: deinit runs when the strong reference count reaches zero.
  3. 3. What is copy-on-write?

    Standard library collections are value types but share a buffer until a mutation forces a real copy.
  4. 4. What happens when Int8 arithmetic overflows with the normal + operator?

    Swift checks overflow at run time and stops the program. Use &+ if you explicitly want wrapping.
  5. 5. Which of these needs import Foundation?

    Date is a Foundation type. print, sorted() and Optional are part of the standard library.

Summary

  • Swift is compiled to native code through parsing, type checking, SIL, LLVM and linking; there is no VM.
  • Types are checked at compile time; inference does not weaken that.
  • ARC frees class instances deterministically when the last strong reference disappears; cycles need weak or unowned.
  • Structs, enums and standard collections are value types with copy-on-write.
  • Failed run-time checks (overflow, bad index, force-unwrapped nil) trap the program.
  • The standard library is always available; Foundation needs import Foundation; packages are built with SwiftPM, which this runner does not offer.

Next: Constants and Variables