Swift Reference

This section documents the Swift 6 language mode as shipped by Swift 6.3, as published in The Swift Programming Language at docs.swift.org, which is the reference these pages are written and verified against. 6.4-beta-only features are always flagged as such — never presented as baseline.

This content was generated with the assistance of AI and should be verified against docs.swift.org before being relied on in production.

This section’s bibliography lists the reference material consulted while preparing these pages.

Welcome to the Swift reference. Swift is a safe, fast and expressive general-purpose language built around value semantics, optionals that make the absence of a value explicit, protocol-oriented design, and — since Swift 6 — a strict, compiler-enforced concurrency model built on structured concurrency and actors. First released by Apple in 2014 and open-sourced in 2015, it reached ABI stability at Swift 5, introduced the opt-in Swift 6 language mode’s strict concurrency checking with Swift 6, and has kept growing through 6.1-6.3 (some shorthand generics, typed throws, InlineArray/Span, integer generic parameters, implicit conformances, default actor isolation, package access) with a 6.4 beta already previewing further additions. It runs on Apple’s platforms, Linux, Windows, WebAssembly, Android and in embedded contexts. This section documents the Swift 6 language mode as shipped by Swift 6.3 (6.3.2), written and verified against The Swift Programming Language (TSPL); features introduced in 6.1-6.3 are labelled with the version that brought them, and 6.4-beta-only material appears only inside clearly marked subsections. Apple-only frameworks — SwiftUI, UIKit, Combine, CoreML, ARKit, Swift Charts — are out of scope for a language reference; Foundation, Dispatch and XCTest appear only where the language pages need them.

New here? Read Getting Started and Lexical Structure and Style first, then the rest of Language fundamentals in order, followed by Types and object modelling — those three groups are the language’s core. From there the remaining groups (errors, safety and memory; concurrency; advanced language features; the standard library and Foundation; interoperability; and tooling and testing) can be read in any order as you need them. Every example in this section, 6.4-beta snippets excepted, is written and verified in intent against the Swift 6.3 toolchain in Swift 6 language mode (swiftc -swift-version 6 / swift run) on macOS and Linux.

Working across languages? The C Reference and C++ Reference cover the languages Swift interoperates with at the lowest level through the Clang importer and -cxx-interoperability-mode, and the Objective-C Reference documents Apple’s other native language, whose frameworks and APIs Swift bridges to directly. Rather than repeating that material, Interoperability with C, Objective-C and C++ cross-references all three.

What’s covered

Getting started

  • Getting Started — what Swift is, a short history from 2014 to Swift 6.3, the language-mode-versus-compiler-version distinction, the available toolchains, the REPL and swiftc, and your first Swift package.

  • Lexical Structure and Style — whitespace, comments and documentation comments, identifiers and backtick-escaped keywords, every literal form, operators and how they are tokenised, semicolons, the API Design Guidelines, MARK/TODO comments, and swift-format.

Language fundamentals

  • Basics: Constants, Variables and Types — let/var, type annotations and inference, printing and interpolation, the integer and floating-point types, numeric literals and conversions, type aliases, Bool, tuples, and assertions/preconditions/fatalError.

  • Optionals — nil and the Optional enum, optional binding, the nil-coalescing operator, forced unwrapping, implicitly unwrapped optionals, optional chaining, the optional pattern, and map/flatMap on optionals.

  • Operators — assignment, arithmetic, comparison, the ternary operator, nil-coalescing, ranges, logical operators and short-circuiting, and the full precedence table.

  • Strings and Characters — string literals, value semantics, concatenation and interpolation, Unicode scalars versus extended grapheme clusters, String.Index, Substring and slicing, comparison, and the UTF-8/UTF-16/scalar views.

  • Collections — Array, Set and Dictionary, slices and ranges as collections, the Sequence/Collection protocol family, the higher-order essentials, lazy, zip, stride, and the Swift 6.2 InlineArray and Span types.

  • Control Flow — for-in, while/repeat-while, if/switch as statements and expressions, exhaustiveness and value binding, continue/break/ fallthrough, guard, defer, and #available/#unavailable.

  • Pattern Matching — the eight pattern kinds and where each may appear, nested destructuring, custom ~= overloads, and matching against ranges and regular expressions.

  • Functions — parameters and return values, argument labels, default and variadic parameters, inout and the copy-in copy-out model, borrowing/consuming, function types, nested functions, @discardableResult, and overloading.

  • Closures — closure expressions and shorthand syntax, trailing closures, capturing values, escaping versus non-escaping, autoclosures, capture lists, and @Sendable closures.

Types and object modelling

  • Enumerations — enum syntax and matching with switch, CaseIterable, associated values, raw values, recursive enums with indirect, OptionSet, and enums as state machines.

  • Structures and Classes — definition syntax, memberwise initializers, value versus reference types, identity operators, copy-on-write, and noncopyable types (~Copyable).

  • Properties — stored and lazy properties, computed properties, property observers, property wrappers, type properties, and the Observation module’s @Observable.

  • Methods and Subscripts — instance and type methods, mutating methods, subscript syntax and variants, callAsFunction, and @dynamicCallable.

  • Inheritance — base classes, subclassing, overriding and super, final, dynamic dispatch and polymorphism, and when to subclass versus compose or use protocols.

  • Initialization and Deinitialization — initializer parameters, default and memberwise initializers, designated versus convenience initializers, two-phase initialization, required and failable initializers, and deinit.

  • Extensions and Nested Types — extension syntax, adding computed properties/initializers/methods/subscripts, retroactive conformance, and nested types for namespacing.

  • Protocols — requirements, protocols as types (any P), conformance via extensions and conditional conformance, synthesized conformances, protocol inheritance and composition, and protocol-oriented design.

  • Generics — generic functions and types, constraints, associated types, generic where clauses, integer generic parameters, and some P as lightweight generic-parameter syntax.

  • Opaque and Boxed Protocol Types — returning some P, boxed protocol (existential) types any P and their runtime cost, opaque parameter types, implicitly opened existentials, and choosing between some, any and explicit generics.

  • Type Casting and Reflection — is, as?, as!, Any versus AnyObject, metatypes, bridging casts to Foundation types, and reflection with Mirror.

Errors, safety and memory

  • Error Handling — the Error protocol, throw, the four ways to handle errors, typed throws, rethrows, Result<Success, Failure>, and defer.

  • Automatic Reference Counting — how ARC works, strong reference cycles between class instances and in closures, resolving them with weak and unowned, and diagnosing leaks.

  • Memory Safety and Unsafe Pointers — the exclusivity rules for inout parameters and mutating methods, and the unsafe pointer layer together with the safe non-owning Span/RawSpan alternatives.

  • Access Control — the six access levels, the guiding principle and defaults, and access levels for custom types, properties, initializers, protocols and generics.

Concurrency

  • Async/Await and Tasks — async functions and await, AsyncSequence, async let, structured concurrency with Task and task groups, cancellation, and task-local values.

  • Actors, Isolation and Sendable — isolation domains, @MainActor, actors and reentrancy, global actors, Sendable and sending, strict concurrency checking, default actor isolation, and the Synchronization module.

  • Dispatch and Legacy Concurrency — Grand Central Dispatch queues, DispatchGroup, barriers and semaphores, Operation/OperationQueue, and wrapping both for async/await.

Advanced language features

  • Advanced Operators — bitwise operators and shifts, overflow operators, operator methods on custom types, and custom operators and precedence groups.

  • Result Builders — @resultBuilder, buildBlock and the other build methods, building a small DSL, and how SwiftUI’s ViewBuilder uses the same mechanism.

  • Key Paths and Dynamic Member Lookup — the KeyPath hierarchy, reading and writing through key paths, and @dynamicMemberLookup.

  • Regular Expressions — regex literals and extended delimiters, the Regex type, typed captures, and the RegexBuilder DSL.

  • Macros — freestanding and attached macros, macro declarations and hygiene, and implementing a macro with swift-syntax.

  • Attributes and Compiler Control — the declaration and type attributes that matter day to day, declaration modifiers, and conditional compilation.

  • Functional Programming — immutability, pure and higher-order functions, composition, currying and recursion, and Optional/Result as containers.

Standard library and Foundation

  • Standard Library Overview — the numeric, Equatable/Hashable/Comparable and ExpressibleBy…​Literal protocols, Sequence/Collection, Optional/Result, and print/readLine.

  • Codable and Serialization — Encodable/Decodable, synthesized conformance, JSONEncoder/JSONDecoder, custom encoding, and parsing XML with Foundation’s XMLParser.

  • Foundation Essentials — Date, Calendar, URL, Data, FileManager, URLSession with async/await, and bridging between Swift and NS types.

Interoperability

Tooling and testing

  • Swift Package Manager — Package.swift and PackageDescription, products and targets, dependency version rules, the swift build/run/test/ package commands, and publishing a package.

  • Build and Tooling — swiftc essentials, language modes versus compiler versions, Swiftly, cross-platform builds, debugging with LLDB, and DocC.

  • Testing — Swift Testing (@Test, #expect, #require, @Suite) and XCTest, @testable import, and a pointer to XCUITest as Apple-platform-only.

Reference

  • Cheat Sheet (PDF) — a single-page, printable Swift quick reference covering types, optionals, strings, collections, control flow, functions and closures, enums, structs and classes, properties, initializers, protocols, generics, error handling, ARC, access levels, concurrency, regex and key paths, macros, attributes, Package.swift, and Swift Testing/XCTest.

Bibliography

The reference material consulted while preparing this section. The Swift Programming Language and docs.swift.org are the primary sources; everything here targets the Swift 6 language mode as shipped by Swift 6.3 unless stated otherwise.

The Swift Programming Language

Swift Documentation hub

swift.org

Swift Evolution and tooling repositories

Apple framework references

Books consulted

  • Hoffman, Jon. Mastering Swift 6: Modern programming techniques for high-performance apps in Swift 6.2, 7th ed. Packt Publishing, 2025. ISBN 978-1-83620-369-8. Consulted as a reference while preparing these pages — see the publisher’s book page, packtpub.com and the code repository.

  • Moon, Keith; Barker, Chris; Bolella, Daniel; Lawlor, Nathan. Swift Cookbook: Proven recipes for developing robust iOS applications with Swift 5.9, 3rd ed. Packt Publishing, 2024. ISBN 978-1-80323-958-3. Consulted as a reference while preparing these pages — see the publisher’s book page, packtpub.com and the code repository.

The books above are consulted references, not the primary source for this section; on any discrepancy, or wherever they are silent on a feature introduced after they were written, TSPL and docs.swift.org win.