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/TODOcomments, andswift-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 —
niland theOptionalenum, optional binding, the nil-coalescing operator, forced unwrapping, implicitly unwrapped optionals, optional chaining, the optional pattern, andmap/flatMapon 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,Substringand slicing, comparison, and the UTF-8/UTF-16/scalar views. -
Collections —
Array,SetandDictionary, slices and ranges as collections, theSequence/Collectionprotocol family, the higher-order essentials,lazy,zip,stride, and the Swift 6.2InlineArrayandSpantypes. -
Control Flow —
for-in,while/repeat-while,if/switchas 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,
inoutand 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
@Sendableclosures.
Types and object modelling
-
Enumerations — enum syntax and matching with
switch,CaseIterable, associated values, raw values, recursive enums withindirect,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
lazyproperties, computed properties, property observers, property wrappers, type properties, and theObservationmodule’s@Observable. -
Methods and Subscripts — instance and type methods,
mutatingmethods, 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,
requiredand failable initializers, anddeinit. -
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
whereclauses, integer generic parameters, andsome Pas lightweight generic-parameter syntax. -
Opaque and Boxed Protocol Types — returning
some P, boxed protocol (existential) typesany Pand their runtime cost, opaque parameter types, implicitly opened existentials, and choosing betweensome,anyand explicit generics. -
Type Casting and Reflection —
is,as?,as!,AnyversusAnyObject, metatypes, bridging casts to Foundation types, and reflection withMirror.
Errors, safety and memory
-
Error Handling — the
Errorprotocol,throw, the four ways to handle errors, typed throws,rethrows,Result<Success, Failure>, anddefer. -
Automatic Reference Counting — how ARC works, strong reference cycles between class instances and in closures, resolving them with
weakandunowned, and diagnosing leaks. -
Memory Safety and Unsafe Pointers — the exclusivity rules for
inoutparameters and mutating methods, and the unsafe pointer layer together with the safe non-owningSpan/RawSpanalternatives. -
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 —
asyncfunctions andawait,AsyncSequence,async let, structured concurrency withTaskand task groups, cancellation, and task-local values. -
Actors, Isolation and Sendable — isolation domains,
@MainActor, actors and reentrancy, global actors,Sendableandsending, strict concurrency checking, default actor isolation, and theSynchronizationmodule. -
Dispatch and Legacy Concurrency — Grand Central Dispatch queues,
DispatchGroup, barriers and semaphores,Operation/OperationQueue, and wrapping both forasync/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,buildBlockand the other build methods, building a small DSL, and how SwiftUI’sViewBuilderuses the same mechanism. -
Key Paths and Dynamic Member Lookup — the
KeyPathhierarchy, reading and writing through key paths, and@dynamicMemberLookup. -
Regular Expressions — regex literals and extended delimiters, the
Regextype, typed captures, and theRegexBuilderDSL. -
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/Resultas containers.
Standard library and Foundation
-
Standard Library Overview — the numeric,
Equatable/Hashable/ComparableandExpressibleBy…Literalprotocols,Sequence/Collection,Optional/Result, andprint/readLine. -
Codable and Serialization —
Encodable/Decodable, synthesized conformance,JSONEncoder/JSONDecoder, custom encoding, and parsing XML with Foundation’sXMLParser. -
Foundation Essentials —
Date,Calendar,URL,Data,FileManager,URLSessionwithasync/await, and bridging between Swift andNStypes.
Interoperability
-
Interoperability with C, Objective-C and C++ — how the Clang importer maps C into Swift, Objective-C interop and bridging, C++ interop, and cross-references to the C, C++ and Objective-C references.
Tooling and testing
-
Swift Package Manager —
Package.swiftandPackageDescription, products and targets, dependency version rules, theswift build/run/test/packagecommands, and publishing a package. -
Build and Tooling —
swiftcessentials, 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
-
The Swift Programming Language (TSPL, Swift 6.4 beta edition; revision history through 2026-07-06) — the primary source every page in this section is written and verified against, including its Document Revision History.
Swift Documentation hub
-
Swift Documentation hub — the index of every DocC archive below.
-
Swift standard library (also mirrored at developer.apple.com).
-
The platform guides: Linux, Windows, WebAssembly, Android, Apple platforms and Embedded Swift.
swift.org
-
The Swift Compiler and LLDB.
Swift Evolution and tooling repositories
-
Swift Evolution and swiftlang/swift-evolution — the accepted proposals cited on individual pages.
-
swift-syntax, swift-format, swift-testing, swift-package-manager, swift-docc and swift-foundation.
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.