Swift Cheatsheet — Concise Reference
A cheatsheet for Swift 5.9 syntax, value types, protocols, and the most-used standard library — covering about 80% of everyday scenarios.
Swift Swift 5.9
LLVM (swiftc / Swift toolchain) · Multi-paradigm (Protocol-oriented · OO · Functional) · Static · Strongly typed
Recommended Learning Path
Start with print and variable bindings → master value types (struct/enum) and Optional → dive into functions, closures, and collections → understand protocol-oriented design and extensions → use do-catch and throws for error handling → write concurrency with async/await and DispatchQueue → then learn URLSession, dates, and build tests as needed. The FAQ section is great for revisiting pitfalls.
1.Hello World & Build Environment
Run Swift programs, SwiftPM projects and the toolchain.
Minimal program
Top-level code is the program entry point. `print` outputs. `import` brings in modules.
Run & build
`swift` runs scripts directly. `swiftc` compiles. `swift run` runs a package.
SwiftPM project
`swift package init` initializes. `Package.swift` is the manifest. `Sources` is the source directory.
`import`
`import` imports a module. `Foundation` is commonly used. Import submodules on demand.
Output & interpolation
`print` / `print(items:)`. String interpolation `\(value)`. Separators and terminators.
Command-line arguments
`CommandLine.arguments` retrieves the arguments. The first is the program path.
Multiple files
Multiple source files in the same package share types. `internal` access level.
Xcode integration
Xcode project organization. targets and schemes. iOS development workflow.
2.Variables & constants
`var` / `let` bindings, type inference, scope, and naming.
`var` & `let`
`let` declares a constant; immutable. `var` declares a variable; mutable. Prefer `let`.
Type inference
The compiler infers types from literals and context. Annotate explicitly in complex cases.
Explicit types
Annotate the type after a colon. Improves readability. Plays nicely with conversions and literals.
Constants
`let` declares a constant. A reference-type constant is an immutable reference. Compile-time constants.
Shadowing
An inner scope's same-named variable shadows the outer one. Common with `if` / `switch` local constants.
Scope
`{}` defines scope. Inner scope can access outer. Outer scope cannot access inner.
Naming conventions
Swift naming conventions: camelCase, clear verbs, avoid abbreviations.
Type conversion
Numeric types require explicit conversion. `init()` constructors. Convert between strings and numbers.
3.Type system
Basic types, tuples, structs, enums, and optionals.
Basic types
`Int`, `Double`, `Bool`, `String`, `Character`. Value types.
Integer types
`Int8`–`Int64` and `UInt` families. Platform `Int`. Overflow handling.
Floating-point
`Float` / `Double` precision. `CGFloat` for UI coordinates. Arithmetic and special values.
Tuples
Compound multi-element values. Named elements. Destructuring. Lightweight data grouping.
Structs
`struct` is a value type. Auto-generated memberwise initializer. Properties and methods.
Enums
`enum` groups related values. Associated values. Raw values. Exhaustive matching.
Optionals
`Optional` represents a possibly-empty value. `T?` syntax. `nil` means no value.
Nested types
Types defined inside other types. Namespace organization. Enums carrying related types.
4.Value types & references
Value semantics, class references, copy-on-write, and memory layout.
Value vs reference
`struct` copies by value semantics. `class` shares by reference. Core language difference.
`class` semantics
`class` is a reference type. Identity is unique. Mutability and thread sharing.
Copy-on-write
Value types like `Array` share storage internally. Copy happens only on mutation.
Identity & equality
`===` is reference identity. `==` is value equality (Equatable). The distinction matters.
`weak` & `unowned`
`weak` is a weak reference; doesn't bump the reference count. `unowned` is an unowned reference. Breaks retain cycles.
`inout` parameters
`inout` parameters are passed by reference. The function modifies the original value. Prefix with `&` at the call site.
Pointer interop
`UnsafePointer` for C interop. Memory-management responsibility. Hazardous territory.
Memory layout
A type's memory layout. Byte alignment. Affects performance and interop.
5.Control flow
`if`, `switch`, `guard`, loops, and optional binding.
`if` / `else`
`if` executes conditionally. `else if` for extra branches. Conditions need no parentheses.
`switch`
`switch` matches exhaustively. Ranges, tuples, bindings. No `break` needed.
`guard`
`guard` exits early. Its `else` must exit the scope. The `else` block can have further branches.
`for`-`in` loops
`for`-`in` iterates over ranges, arrays, and dictionaries. Indexed iteration.
`while` loops
`while` is a conditional loop. `repeat`-`while` executes first, then tests the condition.
`break` & `continue`
`break` exits a loop. `continue` skips the current iteration. Labeled statements break out of nested loops.
`if let`
Optional binding unwrap. guard let exits early. Unpack multiple values simultaneously.
Pattern matching
Patterns in switch/if. case let, where. Type matching.
6.Functions
Function definitions, parameter labels, return values, function types, and closures.
Function definition
func defines functions. Parameters and return values. Call syntax.
Parameter labels
Parameter labels and internal names. _ omits the label. Readability design.
Default parameter values
Default parameter values. Omitted at call site. Must be trailing, or all must have defaults.
Return values
Return value type. Use tuples for multiple values. Implicit return for single expressions.
Variadic parameters
... collects multiple arguments into an array. Any count. Last parameter.
`inout` parameters
inout modifies external variables. & passes by reference. Mutate value types in place.
Function types
Functions as types. Assign, pass as argument, return. First-class citizens.
Closures
Closures capture surrounding context. Trailing closures. Shorthand argument names.
7.Strings
String operations, interpolation, substrings, Unicode, and formatting.
String basics
String is a value type. Literals and mutability. Composed of Characters.
Interpolation
\(expression) embeds values. Type-safe. Any expression.
Concatenation
String concatenation. append. join. += operator.
Multiline strings
Triple-quoted multiline strings. Indent stripping. Inline interpolation. Line breaks preserved.
Common methods
Case changes, search, replace, split, trim. Common string APIs.
Substrings
Substring references the original. Slices return Substring. Convert to String to keep.
Unicode
Characters composed of Unicode scalars. Code points. Extended grapheme clusters.
Formatting
String(format:) C-style formatting. Numeric padding and precision.
8.Collections
Array, Dictionary, Set, higher-order functions, and ranges.
Array
Ordered collection of values. Generic [T]. Add, remove, modify, search.
Array operations
Slice, replace, merge, search. Common higher-order methods.
Dictionary
Key-value collection. [String: T]. Unordered. O(1) lookup.
Set
Unordered collection of unique elements. Hash set. Set operations.
Iteration
Iterate arrays, dictionaries, sets. With index. Reverse. Filtered iteration.
Higher-order functions
map, filter, reduce, compactMap, sorted. Functional processing.
Nested collections
Composing collections. Multi-dimensional arrays, dictionaries of arrays, collections of structs.
Range
Half-open range ..<, closed range .... Array slicing and loops.
9.Memory management
ARC reference counting, weak references, retain cycles, and memory optimization.
ARC
Automatic reference counting manages class instances. Deallocated when count hits zero.
weak/unowned
Weak references do not increment count. Prevent retain cycles. Handle access after deallocation.
Autorelease pool
autoreleasepool defers release. Memory control in large loops.
Copy semantics
Value types are safe to copy. Optimizing large types. Shared vs. unique.
Retain cycles
Two classes strongly referencing each other form a cycle. Memory leak. weak breaks it.
Stack vs heap
Value types on the stack, reference types on the heap. Allocation and performance.
lazy storage
lazy defers initialization. Created only when accessed. Optimizes expensive properties.
Memory optimization
Reduce heap allocations, reuse buffers, avoid large copies. Performance tuning.
10.Classes & protocols
class, inheritance, protocols, extensions, and protocol-oriented design.
class definition
Classes define properties and methods. Reference type. Initializers.
Inheritance
Subclasses inherit from parents. Stored properties, methods. final classes.
Method overriding
override overrides methods, properties, initializers. super calls the parent.
Protocols
protocol defines requirements. Types conform. Core of protocol-oriented design.
Protocol extensions
extension provides default implementations. Constrained extensions. Default methods on protocols.
Extensions
extension adds methods to existing types. Organizes code by category.
Property Observers
willSet/didSet observe property changes. UI updates, validation.
Computed Properties
get/set compute a value. Nothing is stored. Derived data.
11.Error Handling
throws, do-catch, try, defer and custom errors.
Error Protocol
The Error protocol marks a type as an error. Enums define error categories.
throws
throws marks a throwing function. throw raises an error. Callers must handle it.
do-catch
try inside a do block. catch handles the error. Multiple branches.
try Variants
try requires a catch. try? converts to an optional. try! forces it (risk of a crash).
Custom Errors
Errors carry context. LocalizedError provides descriptions. Error codes.
defer Cleanup
defer runs when the scope ends. Cleans up resources. Runs in reverse order.
Fatal Errors
fatalError is an unrecoverable crash. precondition checks a condition.
Result Type
Result<Success, Failure> makes success or failure explicit. Avoids throws.
12.Input and Output
Command-line input, file reading and writing, FileManager and Codable.
Reading Input
readLine reads command-line input. Interactive loops. Parsing numbers.
Reading Files
String(contentsOf:) reads a file. Data for binary. Reading line by line.
Writing Files
Writing strings and Data. Append mode. Atomic writes.
FileManager
File system operations. Create directories, delete, move, check existence.
Output Control
print variants. stderr. Separator and terminator. String descriptions.
Working with Data
Data is a byte container. Converting to and from strings. base64 encoding and decoding.
JSONSerialization
JSON to dictionaries/arrays. Serializing back. The JSONSerialization class.
Codable
Codable serializes automatically. JSONEncoder/Decoder. Protocol driven.
13.Common Pitfalls
The traps Swift beginners fall into most often, and the correct way to write it.
Force Unwrapping
Unwrapping nil with ! crashes. Prefer optional binding and the nil-coalescing operator.
Optional Chaining
?. chains access. If any link is nil the whole result is nil. Assignment works too.
Closure Retain Cycles
A closure capturing self strongly forms a cycle. Use a capture list [weak self].
Array Out of Bounds
An out-of-range index crashes. Access safely with first/last/prefix. Check bounds.
mutating
A struct method that modifies properties needs mutating. Value types are immutable copies.
String Indices
Strings cannot be subscripted by integers. Characters are multi-byte. Use the index methods.
Protocols and Self
Using the Self constraint in protocols. associatedtype. Type erasure.
Implicitly Unwrapped Optionals
T! is an implicitly unwrapped optional. Using it uninitialized crashes. Use with care.
14.Concurrency
GCD, async/await, Task and the actor concurrency model.
GCD Basics
DispatchQueue serial/concurrent queues. Global and main queues.
Dispatch Groups
DispatchGroup waits for multiple tasks to finish. Aggregating batched concurrency.
async/await
Modern Swift concurrency syntax. Async functions and suspension. Structured concurrency.
async let
Runs several async calls concurrently. Binds independent child tasks. Waits in parallel.
Task
Task creates a unit of concurrency. Inherits context. Cancellation and priority.
actor
An actor isolates state. Avoids data races. Accessed through async methods.
Main Thread
UI work must run on the main thread. Hopping between threads. Checking for the main thread.
Thread Safety
Protecting mutable state under concurrent access. Locks, queues, atomic operations.
15.Networking
URLSession, HTTP requests, async networking and working with JSON.
URLSession
URLSession makes network requests. Configuration and delegates. Session types.
GET Requests
Making a GET. Fetching data with async/await. Handling the response status.
POST Requests
Sending a JSON body. Form submissions. Setting Content-Type.
Async Networking
Network calls with async/await. Concurrent requests. Cancelling tasks.
URL Building
URLComponents for safe URL construction. Query-parameter encoding. Path composition.
Downloading Files
Download tasks save files. Progress monitoring. Background downloads.
Network JSON
Request JSON and decode with Codable. Date and strategy handling.
Uploading Files
Multipart form upload. File body. Boundary separator.
16.Date and Time
Date, DateFormatter, calendar arithmetic, and timers.
Date
Date represents a point in time. Timezone-independent absolute instant. Creation and comparison.
Date Formatting
DateFormatter displays dates. Localized formats. Custom formats.
Parsing Dates
Convert strings to Date. Fixed-format parsing. ISO8601 parsing.
Date Components
DateComponents extracts year, month, and day. Calendar component arithmetic.
Calendar Arithmetic
Add or subtract days and months from a date. Next week / next month. Safe Calendar arithmetic.
Time Intervals
Measure code execution time. TimeInterval is in seconds. Performance timing.
Timer
Timers for repeated execution. One-shot timers. RunLoop caveats.
Date Comparison
Compare dates chronologically. Test if they fall on the same day. Sorting and validation.
17.Process and System
Command-line arguments, environment variables, process operations, and file paths.
Command-line arguments
CommandLine retrieves arguments. Handle arguments and options.
Environment Variables
Read environment variables. Set and pass them. Caveats for sensitive data.
Process
Process launches child processes. Execute commands. Capture output.
Path Handling
URL path manipulation. Composition, extensions, filenames. Sandbox directories.
Exit Codes
Program exit code. exit and fatalError. 0 means success, non-zero means failure.
Signal Handling
Catch system signals. SIGINT and others. Graceful exit.
Working Directory
Get and switch the current working directory. Base for relative file paths.
Process File I/O
Read standard input. Write to standard output. Pipe interaction.
18.Regular Expressions
Regex literals, NSRegularExpression, and pattern matching.
Regex Basics
Regex syntax concepts. Character classes, quantifiers, groups.
Regex Literals
Swift 5.7 regex literals /.../. Typed matching. Named captures.
NSRegularExpression
The NSRegularExpression regex engine. Range matching. Compatible with older systems.
Matching
First match, all matches, test if it matches. Retrieve ranges.
Capture Groups
Extract capture group contents. Named captures. Regex group references.
Replacement
Regex text replacement. Templates reference capture groups. Conditional replacement.
Splitting
Split a string by regex. Keep or drop the delimiter. Multiple delimiters.
Common Patterns
Common regex templates for email, URL, numbers, phone numbers, and more.
19.Build and Tooling
swiftc compilation, SwiftPM build, formatting, and linting tools.
swiftc Compilation
Compile a single file from the command line. Generate an executable. Optimization options.
SwiftPM Build
swift build compiles a project. Incremental builds. Release mode.
Running Tests
swift test runs the test suite. XCTest and test targets.
Package.swift
The SwiftPM package manifest. Targets and dependencies. Platform configuration.
SwiftLint
Code style checking. Configure rules. CI integration.
swift-format
The official code formatter. Formatting rules and configuration.
xcodebuild
Command-line build for Xcode projects. Export and archive. CI usage.
Release Process
Version control, build & release, distribution. Release checklist.
Official Links
Direct links to the official docs and resources.
About this Cheatsheet
This page is a self-contained cheatsheet for Swift 5.9, covering the language core and the most common uses of the standard library in real projects — about 80% of everyday use. Content leans toward modern idioms: value types (struct/enum), protocol-oriented design, async/await structured concurrency, if let pattern matching, and Codable serialization. For authoritative references, see the official Swift Language Guide and API Design Guidelines. 19 chapters, each focused on one topic — from your first program to optionals, protocols, concurrency, and common pitfalls. Each chapter is broken into 8 example-driven subsections (5–20 lines each), totalling about 150 topics. Code snippets are deliberately short and self-explanatory. All processing happens in the browser — no uploads, no tracking. This page is part of GuruToolkit's free developer toolkit; code snippets are free to use with no warranty of any kind.
Version 2.1.0