Swift Cheat Sheet
Swift syntax, optional handling, structs versus classes, protocols, and closures for building type-safe iOS and macOS applications.
2 PagesIntermediateMar 28, 2026
Basic Syntax
Variables, control flow, and printing.
swift
import Foundationlet age = 30 // constant (let)var count = 0 // variable (var)let name = "Ada"let pi: Double = 3.14159if age >= 18 { print("\(name) is an adult")}for i in 0..<5 { print("Count: \(i)")}
Optionals
Safely handling the absence of a value.
swift
var middleName: String? = nil // optional, may hold nilif let name = middleName { // optional binding print("Middle name: \(name)")} else { print("No middle name")}let display = middleName ?? "N/A" // nil-coalescing operatorguard let unwrapped = middleName else { fatalError("middleName was nil")}
Protocols & Closures
Interfaces and inline functions.
swift
protocol Greetable { func greet() -> String}struct Person: Greetable { let name: String func greet() -> String { "Hello, \(name)" }}let numbers = [1, 2, 3, 4, 5]let doubled = numbers.map { $0 * 2 } // closure shorthandlet sum = numbers.reduce(0) { $0 + $1 } // 15
Core Keywords
Common Swift language keywords.
- let/var- constant and mutable variable declarations
- struct- value type, copied on assignment
- class- reference type, shared by reference
- protocol- defines a blueprint of methods/properties (like an interface)
- guard- early-exit control flow requiring a condition to hold
- extension- adds functionality to an existing type
- Optional (?/!)- ? declares optional, ! force-unwraps
- enum- value type supporting associated values and pattern matching
Enums with Associated Values
Model states carrying data and match them with switch.
swift
enum Result { case success(data: String) case failure(code: Int, message: String) case loading}let outcome = Result.failure(code: 404, message: "Not Found")switch outcome {case .success(let data): print("Data: \(data)")case .failure(let code, let message): print("Error \(code): \(message)")case .loading: print("Loading...")}
Structs & Value Semantics
Value types with mutating methods and computed properties.
swift
struct Point { var x: Double var y: Double var magnitude: Double { // computed property (x * x + y * y).squareRoot() } mutating func moveBy(dx: Double, dy: Double) { x += dx y += dy }}var a = Point(x: 3, y: 4)let b = a // copy, not referencea.moveBy(dx: 1, dy: 0)print(b.x) // 3 - unchanged
Error Handling
Throwing functions with do/catch and try variants.
swift
enum NetworkError: Error { case badURL case timeout}func fetch(_ url: String) throws -> String { guard url.hasPrefix("https") else { throw NetworkError.badURL } return "data"}do { let data = try fetch("http://x")} catch NetworkError.badURL { print("invalid URL")} catch { print("other: \(error)")}let safe = try? fetch("https://x") // Optional, nil on throw
Property Wrappers & Attributes
Common Swift and SwiftUI property annotations.
- @State- SwiftUI local mutable view state
- @Binding- two-way reference to state owned elsewhere
- @Published- emits changes from an ObservableObject
- @escaping- closure that outlives the function call
- lazy var- property computed on first access
- weak / unowned- non-retaining references to break cycles
- @objc- expose a declaration to Objective-C runtime
- willSet / didSet- property observers around value changes
Pro Tip
Prefer struct over class by default in Swift — value semantics avoid unexpected shared mutable state; reach for class only when you need reference identity or inheritance.
Was this cheat sheet helpful?
Explore Topics
#Swift#SwiftCheatSheet#Programming#Intermediate#BasicSyntax#Optionals#ProtocolsClosures#CoreKeywords#OOP#Functions#CheatSheet#SkillVeris