Swift — Reference
Source: https://docs.swift.org/swift-book/
Swift
- Created: 2014 by Chris Lattner & team at Apple; open-sourced 2015 (Apache 2.0)
- Latest stable: Swift 6.3 (2026-03-24); Swift 6.3.1 current
- Paradigms: multi-paradigm — object-oriented, protocol-oriented, functional, imperative, generic, declarative (SwiftUI), structured concurrent
- Typing: static, strong, with type inference; protocols (with associated types) are the abstraction primitive
- Memory: ARC (Automatic Reference Counting) for classes; value types (struct/enum) on stack or copy-on-write
- Compilation: AOT compiled via LLVM to native; ABI-stable on Apple platforms (since 5.0); WebAssembly + embedded targets
- Primary domains: Apple platforms (iOS, macOS, watchOS, tvOS, visionOS), server-side (Vapor), systems programming, embedded firmware (Swift for embedded), cross-platform mobile/desktop
- Official docs: https://docs.swift.org/swift-book/
1. At a glance
- Stewarded by the Swift project under Apple; community governance via Swift Evolution (SE proposals on GitHub).
- One implementation:
swiftc(LLVM-based). Swift Package Manager is the official build system. - Supported on macOS, Linux, Windows, Android (community), and WASM (SwiftWasm).
- ABI stability since Swift 5.0 (2019) means the runtime ships in the OS on Apple platforms.
2. Getting started
-
Install: macOS: install Xcode (App Store) — bundles toolchain. Linux/Windows: download from https://www.swift.org/install/. macOS standalone:
brew install swift(community) or use Xcode Command Line Tools. -
Version manager:
swiftly(official, https://www.swift.org/install/swiftly/) for managing multiple toolchains.swiftenvis community-popular. -
Hello, world:
print("Hello, world!")Or as a script:
swift hello.swift. Package:swift package init --type executable && swift run. -
Project layout:
Package.swiftmanifest at root;Sources/<Target>/*.swift;Tests/<Target>Tests/*.swift. Multi-target/multi-product packages supported. -
Build tool: Swift Package Manager (SwiftPM):
swift build,swift test,swift run,swift package. Xcode also builds Swift via its own pipeline. -
REPL/playground:
swift(REPL); Xcode Playgrounds (interactive, with timeline view); Swift Playgrounds app on iPad/Mac.
3. Basics
- Primitives:
Bool,Int(andInt8…Int64,UInt*),Float,Double,Float16/Float80,Character(extended grapheme cluster),String. Literals:0x,0b,0o,_separators (1_000_000), exponent form. - Variables:
let x = 1(immutable),var x = 1(mutable). Type annotations:let x: Int = 1. Block-scoped. Optionals:var s: String? = nil, unwrap withif let/guard let/!/??. - Control flow:
if/else,if/guard letfor optional binding,switch(exhaustive, with pattern matching, value binding,whereclauses),for x in seq,while,repeat-while.if/switchare expressions since Swift 5.9.deferfor cleanup. - Functions: named & external param labels (
func greet(person name: String)), default values, variadic (Int...), inout (inout), throws/async modifiers. Closures{ (x: Int) -> Int in x + 1 }with shorthand{ $0 + 1 }. First-class functions; trailing closure syntax. - Strings: Unicode-correct (extended grapheme clusters); interpolation:
"Hello \(name), score: \(score)". Multi-line raw:"""..."""; raw strings#"\n"#; regex literals/pattern/(Swift 5.7+). - Collections:
Array<T>([T]),Dictionary<K, V>([K: V]),Set<T>, tuples(Int, String),Optional<T>(T?),Range/ClosedRange. All value-typed, copy-on-write.
4. Intermediate
- Generics:
func swap<T>(_ a: inout T, _ b: inout T), constrained<T: Comparable>, where clauses (where T.Element: Hashable), associated types in protocols, opaque return typessome View, existential typesany Equatable(Swift 5.6+), primary associated types (Swift 5.7+). - Modules/packages: Swift compiles in modules (one per target).
import Foundation. Packages declared inPackage.swift(manifest is itself Swift code). Public/internal/fileprivate/private/open access levels. - Error handling:
throws+try/try?/try!/do-catch. Errors conform toErrorprotocol. Typed throws (Swift 6+:throws(MyError)).Result<Success, Failure>for storing errors as values.fatalError/precondition/assertfor unrecoverable. - Concurrency (Swift 5.5+):
async/awaitfunctions, structured concurrency viaasync let,TaskGroup,withCheckedContinuation. Actors isolate mutable state.@MainActorpins to main thread.Sendablemarker protocol checked at compile time.AsyncSequence+for await. Swift 6 introduces full strict-concurrency by default. - I/O & networking:
FoundationEssentials/Foundation—FileManager,URL,Data,URLSession(HTTP),JSONEncoder/Decoder. Swift NIO for low-level async I/O / networking on server. - Stdlib highlights:
Sequence/Collection/RangeReplaceableCollection/RandomAccessCollectionprotocols (the spine of the stdlib),Codable,Hashable,Equatable,Comparable,CustomStringConvertible,KeyPath,Result,Duration(5.7+),Regexbuilders (5.7+).
5. Advanced
- Memory & ARC: classes are reference-counted; strong by default, weak (zeroes on dealloc), unowned (no count, must outlive). Retain cycles are the main hazard; resolved with
[weak self]capture lists in closures. Value types (struct/enum) avoid ARC entirely. - Concurrency deep dive: cooperative thread pool (one thread per core, no thread explosion), tasks suspend at
awaitand resume on (potentially different) thread. Actors serialize their state via internal queue. Custom executors (Swift 5.9+). Task locals,TaskGroup,AsyncStream.@MainActorguarantees main-thread access. Sendable conformance is the gatekeeper for thread safety. - FFI/interop: C interop is built-in:
import CFoo, no header generation needed. C++ interop (Swift 5.9+,import CxxFoo) — bidirectional. Objective-C interop (transparent on Apple platforms;@objc,@objcMembers,NSObject). Swift can be embedded in C/C++ apps via-emit-library. - Reflection:
Mirrorfor runtime introspection (limited; mostly for printing/debugging).KeyPath<Root, Value>for type-safe value access. Dynamic member lookup via@dynamicMemberLookup. - Performance tooling: Instruments (Time Profiler, Allocations, Leaks, System Trace, Swift Concurrency template),
os_signpost, swift-collections-benchmark,swift package -c release,-O/-Osize/-Onone,@inlinable/@inline(__always), profile-guided optimization, whole-module optimization (-whole-module-optimization).
6. God mode
- Result builders (
@resultBuilder): the engine behind SwiftUI’s declarative DSL — turn a block of expressions into a tree-build call sequence. - Property wrappers (
@propertyWrapper): inject behavior into property storage (@Published,@State,@Binding,@Environment,@AppStorage). - Macros (Swift 5.9+):
@freestanding(expression),@freestanding(declaration),@attached(member),@attached(peer),@attached(extension). Implemented in Swift, run by SwiftSyntax in a separate compiler plugin process. Examples:#URL("..."),@Observable,@Model(SwiftData). - Opaque types vs existentials:
some Protocol(compile-time, single concrete type, zero overhead) vsany Protocol(existential box, dynamic dispatch).anytypes now require explicit keyword. @_specialize/@inlinable/@usableFromInline: force generic specialization across module boundaries; ABI-aware.- ABI stability: Swift 5.0+ runtime ships in OS; library evolution (
-enable-library-evolution) keeps frameworks ABI-stable across recompilation. - Swift runtime metadata: every type has runtime metadata (size, alignment, witness tables). Inspect via swift-demangle, swift_demangle API, or
nmon the binary. - Mach-O inspection:
otool -L(libs),nm -m,swift demangle(mangled names), Hopper/Ghidra for binary RE. - C++ interop (Swift 5.9+): import C++ headers directly; methods, templates (limited), inheritance, smart pointers — bidirectional with caveats.
- Structured concurrency internals: Tasks are heap-allocated thunks scheduled by the cooperative pool; child tasks inherit priority and cancellation; the runtime uses continuation-passing at suspension points.
- Witness tables: vtables for protocol conformance; one witness table per (Type, Protocol) pair.
- Swift for Embedded:
-enable-experimental-feature Embeddedstrips runtime, no ARC overhead, no metadata — targets bare-metal microcontrollers. - SwiftSyntax + swift-syntax as canonical parser, used by macros, swiftformat, sourcery, etc.
7. Idioms & style
- Naming: types
PascalCase, methods/properties/parameterscamelCase. Verbose, descriptive method names:array.removeAll(where:),subviews.insert(_:at:). Prefer fluent API design. - Formatter:
swift-format(official, Apple) andSwiftFormat(community, Nick Lockwood) are dominant. Linter:SwiftLintis the de facto. - Idiomatic Swift: value types by default, classes only when identity / shared mutable state required; protocol-oriented (compose with protocols + extensions instead of inheritance);
guardfor early exit,deferfor cleanup; closures with trailing closure syntax; named arguments at call sites; avoid force-unwrap (!) outside throwaway code; preferResult/throwsover sentinels; let the compiler infer types when obvious. API Design Guidelines are canonical. - Reviewers look for: retain cycles in closures (missing
[weak self]), force unwraps, unhandled error paths, missingSendableconformance, blocking calls inside actors, view body purity (in SwiftUI), wrong access level (defaultinternaloften too lax for libraries).
8. Ecosystem
- Apple platform UI: SwiftUI (declarative), UIKit (iOS/iPadOS/tvOS), AppKit (macOS), WatchKit, RealityKit (visionOS).
- Data/persistence: SwiftData (modern, macro-driven), Core Data, GRDB (SQLite), Realm.
- Server-side: Vapor (most popular framework, async/await native), Hummingbird, Kitura (deprecated), Smoke (Amazon).
- Networking: URLSession (stdlib), Alamofire, swift-nio (low-level), AsyncHTTPClient.
- Cross-platform UI: The Composable Architecture (TCA), PointFree libraries, swift-collections (deque, ordered set/dict).
- Cloud: Soto (AWS SDK), AWS SDK for Swift (official), swift-aws-lambda-runtime.
- Testing: XCTest (stdlib), swift-testing (newer, macro-based, Swift 6), Quick/Nimble (BDD), SnapshotTesting (Point-Free), ViewInspector (SwiftUI).
- Doc tools: DocC (official, ships with toolchain) — generates HTML + Xcode-integrated docs from
///comments and.docccatalogs. - Notable users: Apple (all platforms), Airbnb, Lyft, Uber (rebuilt iOS app), Slack, Khan Academy, Duolingo, LinkedIn, IBM (server), Square.
9. Gotchas
- Optionals + force-unwrap (
!): crash on nil. Useif let/guard let/??. Implicitly-unwrapped optionals (Int!) compound the risk. - Retain cycles in closures:
selfcaptured strongly inside a closure stored onself. Use[weak self]and unwrap. - Value types copy on assign: large structs can be expensive — but COW (copy-on-write) saves arrays/strings/dicts.
- Protocol with associated types (PATs) cannot be used as existentials directly without
anykeyword (Swift 5.6+). @MainActorand async: hopping toMainActorhas cost; over-isolating UI code into background actors then back fights the runtime.- String indexing is not Int:
s[1]doesn’t compile — useString.Index(s[s.index(s.startIndex, offsetBy: 1)]). Designed against grapheme bugs but verbose. - Capturing inout in closures is forbidden because of escape semantics.
@objcrequires Foundation/ObjC runtime — not available on pure Linux without-DFOUNDATION_NOSYNC.- Strict concurrency (Swift 6) turns “data race” warnings into errors; many existing libraries don’t conform yet.
- Generic specialization opacity: across module boundaries, generics are dispatched via witness tables unless
@inlinable(with cost to ABI stability). as!vsas?: force-cast crashes on failure.- Property wrappers fight inheritance: classes with wrapped properties have surprising init requirements.
- Async sequence iteration is not cancelled unless you check
Task.isCancelledor your async source supports it.
10. Citations
- The Swift Programming Language (book): https://docs.swift.org/swift-book/
- Swift.org docs hub: https://www.swift.org/documentation/
- Swift 6.3 release post (2026-03-24): https://www.swift.org/blog/
- Swift Evolution (proposals): https://github.com/swiftlang/swift-evolution
- API Design Guidelines: https://www.swift.org/documentation/api-design-guidelines/
- Swift Package Manager docs: https://www.swift.org/documentation/package-manager/
- DocC documentation: https://www.swift.org/documentation/docc/
- Swift Concurrency Manifesto / docs: https://docs.swift.org/swift-book/documentation/the-swift-programming-language/concurrency/
- Macros (Swift 5.9): https://docs.swift.org/swift-book/documentation/the-swift-programming-language/macros/
- swift-format: https://github.com/swiftlang/swift-format
- SwiftLint: https://github.com/realm/SwiftLint
- Swift on Server (Vapor + ecosystem): https://swift.org/server/