SwiftPrintable

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.

Back to the Swift tutorial

Basics

SyntaxWhat it doesLesson
print("Hello")Print a lineIntroduction
let x = 1 / var y = 2Constant / variableVariables & Constants
let price: Double = 9.99Explicit type annotationVariables & Constants
7 / 2 7 % 2 7.0 / 2Integer division, remainder, decimal divisionNumbers & Operators
Double(n) Int(3.9)Convert between number typesNumbers & Operators
Int.random(in: 1...6)Random numberNumbers & Operators

Strings & optionals

SyntaxWhat it doesLesson
"Hi \(name), \(a + b)"String interpolationStrings
s.count s.uppercased() s.hasPrefix("a")Common string membersStrings
s.split(separator: ",") arr.joined(separator: ", ")Split and joinStrings
""" multi-line """Multi-line stringStrings
var s: String? = nilOptional typeOptionals
if let s { } guard let s else { return }Unwrap safelyOptionals
s?.count ?? 0Optional chaining and defaultOptionals

Control flow & functions

SyntaxWhat it doesLesson
let x = c ? a : bTernary conditionalif & switch
switch n { case 1, 2: ...; case 3...9: ...; default: ... }switch with values and rangesif & switch
for i in 1...5 0..<n stride(from: 10, to: 0, by: -2)Loops and rangesLoops
while c { } repeat { } while cCondition loopsLoops
func greet(_ name: String, from city: String = "Leeds") -> StringLabels and default valuesFunctions
func swap(_ a: inout Int, _ b: inout Int)inout parametersFunctions

Collections & closures

SyntaxWhat it doesLesson
var a = [1, 2] a.append(3) a.firstArray basicsArrays
a.sorted() a.contains(2) a.firstIndex(of: 2)Search and sortArrays
var d = ["a": 1] d["a", default: 0]Dictionary and default lookupDictionaries & Sets
Set([1, 2]) a.union(b) a.intersection(b)SetsDictionaries & Sets
a.filter { $0 > 0 }.map { $0 * 2 }Filter and transformClosures
a.reduce(0, +) a.compactMap { Int($0) }Combine and drop nilsClosures
let f: (Int) -> Int = { $0 * 2 }Closure with a function typeClosures

Types

SyntaxWhat it doesLesson
struct Point { var x = 0; var y = 0 }Struct with memberwise initStructs
mutating func move()Method that changes a structStructs
class Account { init(...) { } }Class with an initializerClasses
class Saver: Account { override func f() { } }InheritanceClasses
enum Size: String, CaseIterable { case s, m, l }Enum with raw valuesEnums
case failed(message: String)Associated valuesEnums
protocol Named { var name: String { get } }ProtocolProtocols
struct User: Equatable, Hashable, IdentifiableStandard protocolsProtocols
extension String { var isEmail: Bool { ... } }ExtensionExtensions

Advanced Swift

SyntaxWhat it doesLesson
func f() throws do { try f() } catch { }Throw and catch errorsError Handling
try? f() defer { } Result<T, E>Optional try, clean-up and ResultError Handling
func largest<T: Comparable>(_ a: [T]) -> T?Generic function with a constraintGenerics
weak var delegate: D? { [weak self] in }Break reference cyclesMemory & ARC
func load() async throws try await load()async/awaitConcurrency
async let a = f() Task { } actor Cache { }Parallel work and actorsConcurrency
try JSONDecoder().decode(T.self, from: data)Decode JSONCodable & JSON
VStack { Text("Hi") }.padding()SwiftUI views and modifiersSwiftUI Basics
@State @Binding @Observable @EnvironmentSwiftUI data flowSwiftUI State
NavigationStack { List(items) { ... } }Lists and navigationLists & Navigation
@Test func f() { #expect(x == 1) }Unit testTesting

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