Swift Cheat Sheet
Constants, strings, optionals, switch, loops, functions, closures, collections, structs, classes, enums, protocols, errors, generics, async/await, Codable, SwiftUI and tests on one printable page.
Strings & optionals
| Syntax | What it does | Lesson |
|---|
"Hi \(name), \(a + b)" | String interpolation | Strings |
s.count s.uppercased() s.hasPrefix("a") | Common string members | Strings |
s.split(separator: ",") arr.joined(separator: ", ") | Split and join | Strings |
""" multi-line """ | Multi-line string | Strings |
var s: String? = nil | Optional type | Optionals |
if let s { } guard let s else { return } | Unwrap safely | Optionals |
s?.count ?? 0 | Optional chaining and default | Optionals |
Control flow & functions
| Syntax | What it does | Lesson |
|---|
let x = c ? a : b | Ternary conditional | if & switch |
switch n { case 1, 2: ...; case 3...9: ...; default: ... } | switch with values and ranges | if & switch |
for i in 1...5 0..<n stride(from: 10, to: 0, by: -2) | Loops and ranges | Loops |
while c { } repeat { } while c | Condition loops | Loops |
func greet(_ name: String, from city: String = "Leeds") -> String | Labels and default values | Functions |
func swap(_ a: inout Int, _ b: inout Int) | inout parameters | Functions |
Collections & closures
| Syntax | What it does | Lesson |
|---|
var a = [1, 2] a.append(3) a.first | Array basics | Arrays |
a.sorted() a.contains(2) a.firstIndex(of: 2) | Search and sort | Arrays |
var d = ["a": 1] d["a", default: 0] | Dictionary and default lookup | Dictionaries & Sets |
Set([1, 2]) a.union(b) a.intersection(b) | Sets | Dictionaries & Sets |
a.filter { $0 > 0 }.map { $0 * 2 } | Filter and transform | Closures |
a.reduce(0, +) a.compactMap { Int($0) } | Combine and drop nils | Closures |
let f: (Int) -> Int = { $0 * 2 } | Closure with a function type | Closures |
Types
| Syntax | What it does | Lesson |
|---|
struct Point { var x = 0; var y = 0 } | Struct with memberwise init | Structs |
mutating func move() | Method that changes a struct | Structs |
class Account { init(...) { } } | Class with an initializer | Classes |
class Saver: Account { override func f() { } } | Inheritance | Classes |
enum Size: String, CaseIterable { case s, m, l } | Enum with raw values | Enums |
case failed(message: String) | Associated values | Enums |
protocol Named { var name: String { get } } | Protocol | Protocols |
struct User: Equatable, Hashable, Identifiable | Standard protocols | Protocols |
extension String { var isEmail: Bool { ... } } | Extension | Extensions |
Advanced Swift
| Syntax | What it does | Lesson |
|---|
func f() throws do { try f() } catch { } | Throw and catch errors | Error Handling |
try? f() defer { } Result<T, E> | Optional try, clean-up and Result | Error Handling |
func largest<T: Comparable>(_ a: [T]) -> T? | Generic function with a constraint | Generics |
weak var delegate: D? { [weak self] in } | Break reference cycles | Memory & ARC |
func load() async throws try await load() | async/await | Concurrency |
async let a = f() Task { } actor Cache { } | Parallel work and actors | Concurrency |
try JSONDecoder().decode(T.self, from: data) | Decode JSON | Codable & JSON |
VStack { Text("Hi") }.padding() | SwiftUI views and modifiers | SwiftUI Basics |
@State @Binding @Observable @Environment | SwiftUI data flow | SwiftUI State |
NavigationStack { List(items) { ... } } | Lists and navigation | Lists & Navigation |
@Test func f() { #expect(x == 1) } | Unit test | Testing |
How to use this Swift cheat sheet
This Swift cheat sheet collects the syntax you'll reach for most often, in the same order as the course: constants and variables, strings, optionals, conditions and loops, functions and closures, collections, structs, classes, enums and protocols, errors, generics, concurrency, Codable, SwiftUI and tests. Each row links to the lesson that explains it with examples and common mistakes.
Keep it open while you practise. When you can't remember the shape of guard let, how to write a trailing closure, or which property wrapper a child view needs, a quick look here is faster than a search. Type part of a keyword into the filter box to jump straight to it, or print the page and keep it beside your keyboard.
Swift gotchas worth remembering
- let is the default. Use
let unless a value really changes. The compiler warns when a var is never mutated, and constants make code easier to reason about. - Force unwrapping crashes.
value! stops the app if the optional is nil. Prefer if let, guard let or a default with ??, and keep ! for values that truly can't be missing. - Structs are copied, classes are shared. Changing a copied struct leaves the original untouched; changing a class instance through any reference changes it everywhere. That's why SwiftUI models data with structs.
- Methods that change a struct need mutating. Without the keyword, the compiler refuses to let a struct method change its own properties.
- Switch must be exhaustive. Every possible value needs a case, or a
default. With enums, leaving out default is often better, because the compiler then reminds you when a new case is added. - Strings aren't indexed by Int.
text[0] doesn't compile. Use text.first, text.prefix(3) or String.Index methods, because Swift strings are made of full Unicode characters. - Closures capture strongly. A closure stored on an object that refers to
self creates a retain cycle. Write [weak self] in the capture list when the closure outlives the call. - @State belongs to the view that owns it. Pass it down to child views as a
@Binding rather than creating a second copy.
A quick revision routine
Open a Swift playground in Xcode or the Swift Playgrounds app, and retype one section of this sheet from memory each day. Run the Swift quiz at the end of the week to check which sections need another look.
The Swift lessons behind this cheat sheet