Anatomy of a Swift file
Swift is a powerful, general-purpose, multi-paradigm programming language for Apple platforms and beyond, known for its safety, speed, and expressive syntax.
File extensions: .swift
Every part of the example below is labelled and explained. This page is one of 55 annotated tours on AnatomyOf, a free, open-source project by LunarWerx Studios.
What is inside a Swift file
Import statement
Brings in modules, frameworks, or libraries.
import Foundation makes an entire module's types and functions available in the current file. The standard library itself (Swift) is imported implicitly everywhere, so an explicit import is only needed for additional modules like Foundation, UIKit, or a third-party package pulled in through Swift Package Manager. Imports are file-scoped: a module imported in one file is not automatically visible in another file of the same target. Xcode and swiftc resolve module names against build settings and package dependencies, and an unused import produces only a compiler warning, not an error.
Comment
Single-line (//) or block (/* ... */), ignored by the compiler.
A double slash starts a comment that runs to the end of the line. A block comment opens with /* and closes with */, and unlike C, Swift block comments can nest inside one another, which makes it safe to comment out a region that already contains a block comment. A comment written with three slashes (///) or in /** ... */ form becomes documentation markup: Xcode renders it in Quick Help and jump-to-definition popovers, and it supports lightweight markup like - Parameter and - Returns fields.
Protocol definition
Defines a blueprint of methods and properties a type can adopt.
A protocol declares requirements (properties, methods, or initializers) without providing an implementation. var greeting: String { get } requires a readable greeting property; any type that conforms must supply one, whether stored or computed. Any type can conform to any number of protocols, which is how Swift shares behavior across unrelated struct, class, and enum types without single inheritance. Protocol extensions can supply default implementations for a requirement, so conforming types only need to override the parts that differ. This "protocol-oriented" style is idiomatic Swift: code i
Struct definition
Defines a value type with properties and methods.
struct Person: Greetable declares a new value type that conforms to the Greetable protocol; the colon introduces the conformance list the same way it would list a superclass for a class. Structs bundle stored properties and methods together, and Swift automatically synthesizes a memberwise initializer when no custom init is defined. Because a struct is a value type, assigning it to another variable or passing it to a function copies its value rather than sharing a reference, mutating the copy never affects the original. This is a deliberate contrast with class, a reference type; Apple's guidan
Property
Stored (let/var) or computed variables within a type.
A stored property holds a value directly, declared with let for a constant or var for one that can change after initialization; let name: String can never be reassigned once set, while var age: Int can. Type annotations like : String are often optional (Swift infers the type from an initial value) but are required here because these properties get their values later, from an initializer. A computed property such as var greeting: String { ... } has no storage of its own; instead its body runs every time the property is read and returns a freshly computed value. Computed properties can also expo
String interpolation
Embeds expressions in strings using \(...).
A backslash followed by parentheses, \(name), evaluates the expression inside and inserts its textual representation directly into the surrounding string literal. Any expression is allowed, not just a simple variable, \(alice.age >= 18 ? "adult" : "minor") works just as well as \(name). Interpolation calls the same description machinery used by String(describing:), so a custom type can control how it appears in interpolated strings by conforming to CustomStringConvertible. Because the escape sequence is \(...) rather than a $-prefixed marker, a literal dollar sign never needs special escaping
Method definition (func)
Defines a reusable block of code within a type.
The func keyword introduces a function or, when written inside a type, a method. func greet() { print(greeting) } takes no parameters and returns nothing; a method with a return value declares it after an arrow, as in func greet() -> String. Parameters can carry an external argument label distinct from the internal name used in the body, which is why Swift call sites often read like natural language. Methods that need to mutate a struct's own stored properties must be marked mutating, since methods are non-mutating by default on value types. This restriction does not apply to classes, whose me
Extension
Adds functionality to an existing type.
extension Person { ... } adds new methods, computed properties, or protocol conformances to Person without touching its original declaration or needing access to its source. Extensions work on types you don't own too, including types from the standard library or a third-party framework. A common pattern splits a type's protocol conformances into separate extensions, one per protocol, so each block reads as a self-contained implementation of that requirement. Extensions cannot add new stored properties, since that would change the type's memory layout after the fact: only computed properties, m
Variable declaration (let/var)
let for constants, var for variables.
Outside of a type, let and var declare local or global bindings the same way they declare stored properties: let fixes a name to a value permanently, while var allows reassignment. Swift infers the type from the assigned expression, so var alice = Person(name: "Alice", age: 30) needs no explicit type annotation. Swift strongly favors let. A variable should only be declared var when the code genuinely reassigns it later, and the compiler emits a warning when a var is never mutated, nudging it back to a constant. This default-to-immutable habit catches accidental reassignment at compile time rat
Object instantiation & method call
Creating an instance and executing its methods.
Person(name: "Alice", age: 30) calls the memberwise initializer Swift synthesized for the struct, supplying a value for every stored property by its argument label. Once alice exists, dot syntax reaches its members: alice.greet() calls a method, and a call like alice.celebrateBirthday() can just as easily invoke a method added later through an extension. The caller cannot tell the difference. Because Person is a struct, alice owns its own independent copy of the data; assigning alice to another variable would copy it, and mutating one copy would never be visible through the other. A class inst
Control flow (conditional & loop)
Executes code based on logic (if, guard, switch) or repeatedly (for, while).
if/else branches on a Bool condition with no parentheses required around it, though the branch bodies always need braces. guard is Swift's complementary form: guard condition else { return } states a requirement up front and exits early when it fails, which keeps the "happy path" unindented for the rest of the function. switch must be exhaustive over its input and supports rich pattern matching, including ranges and tuples, well beyond simple equality checks. for i in 1...3 iterates the closed range 1...3, which includes both endpoints. The half-open operator ..< would exclude the upper bound.
Official Swift site · All languages on AnatomyOf
The interactive tour needs JavaScript. Enable it to hover a callout and trace it into the code.