Cheatsheets / Swift

Swift Cheatsheet

Complete Swift reference. Hit Ctrl+P to print.

Variables & Types

let name = "Alice"Immutable constant
var count = 0Mutable variable
let x: Int = 42Explicit type annotation
Int, Double, Float, Bool, String, CharacterCommon value types
let big: Int64 = 9_000_000_000Underscore separators in literals
let hex = 0xFF; let bin = 0b1010Hex and binary literals
let x: Int? = nilOptional - may hold a value or nil
let x: Int! = 42Implicitly unwrapped optional - use sparingly
typealias Meters = DoubleType alias
let tuple = (200, "OK")Unnamed tuple
let res = (code: 200, msg: "OK"); res.codeNamed tuple - access by label

Strings

"Hello, \(name)!"String interpolation
"""multi\nline"""Multi-line string literal
s.countNumber of characters
s.isEmptyTrue if empty string
s.uppercased() / s.lowercased()Change case
s.hasPrefix("Hello") / s.hasSuffix("!")Prefix/suffix check
s.contains("world")Substring check
s.replacingOccurrences(of: "a", with: "b")Replace substring
s.components(separatedBy: ",")Split string into array
s.trimmingCharacters(in: .whitespaces)Trim whitespace
Int("42")Parse string to Int - returns Optional
String(42)Convert Int to String

Optionals

if let name = optName { }Optional binding - unwrap if non-nil
if let name { }Shorthand optional binding (Swift 5.7+)
guard let name = optName else { return }guard let - exit scope if nil
let n = opt ?? 0Nil-coalescing - use default if nil
opt?.propertyOptional chaining - nil if opt is nil
opt!Force unwrap - crashes if nil
if let a = opt1, let b = opt2 { }Bind multiple optionals
while let item = iter.next() { }Optional binding in while loop
let x = try? parse(s)Convert throwing call to Optional

Control Flow

if x > 0 { } else if x < 0 { } else { }if / else if / else
switch x { case 1: ... case 2, 3: ... default: ... }switch - no fallthrough by default
switch x { case let n where n > 0: ... }switch with where clause
switch shape { case .circle(let r): ... }switch on enum with associated value
fallthroughExplicit fallthrough to next case
for i in 0..<10 { }Half-open range (0 to 9)
for i in 0...10 { }Closed range (0 to 10 inclusive)
for item in array { }Iterate over collection
for (i, v) in array.enumerated() { }Iterate with index
for (k, v) in dict { }Iterate over dictionary
where i.isMultiple(of: 2)for loop filter
while x > 0 { }while loop
repeat { } while x > 0do-while equivalent
break / continueExit loop / skip iteration
guard condition else { return }Early exit - bindings available after
defer { cleanup() }Run code when scope exits - LIFO order

Functions

func greet(name: String) -> String { "Hello \(name)" }Function with argument label
greet(name: "Alice")Call with argument label
func greet(_ name: String)_ removes external label
func move(from src: String, to dst: String)External and internal labels
func greet(name: String = "World")Default parameter value
func sum(_ nums: Int...) -> IntVariadic parameter
func swap(_ a: inout Int, _ b: inout Int)inout - modify caller variable
swap(&x, &y)Call inout function - pass with &
func apply(_ fn: (Int) -> Int, to x: Int) -> IntFunction parameter
let double: (Int) -> Int = { $0 * 2 }Closure with shorthand argument name
{ x, y in x + y }Closure with named parameters
array.sorted { $0 < $1 }Trailing closure syntax
func id<T>(_ x: T) -> TGeneric function
@discardableResult func load() -> DataSuppress unused-result warning

Classes, Structs & Enums

struct Point { var x: Double; var y: Double }Struct - value type, copied on assignment
class User { var name: String; init(name: String) { self.name = name } }Class - reference type
class Admin: User { override func greet() { } }Class inheritance
final class Token { }final - cannot be subclassed
required init()Required initializer - subclasses must implement
convenience init() { self.init(name: "default") }Convenience initializer
deinit { cleanup() }Deinitializer - called on deallocation (classes only)
var computed: Int { get { } set { } }Computed property
var lazy: Data = { loadData() }()Lazy property - initialized on first access
willSet / didSetProperty observers
static var count = 0Type property
mutating func reset()mutating - struct method that modifies self
enum Direction { case north, south, east, west }Enum
enum Result { case success(Data); case failure(Error) }Enum with associated values
enum Planet: Int { case mercury = 1, venus, earth }Raw value enum
Planet(rawValue: 3)Create enum from raw value - returns Optional
indirect enum Tree { case leaf(Int); case node(Tree, Tree) }Recursive enum

Protocols & Generics

protocol Greetable { func greet() -> String }Protocol definition
struct User: Greetable, Codable { }Conform to multiple protocols
extension User: Greetable { func greet() -> String { name } }Protocol conformance in extension
protocol Container { associatedtype Item }Protocol with associated type
func printAll<T: Greetable>(_ items: [T])Generic with protocol constraint
func printAll(_ items: some Greetable)some - opaque type (Swift 5.7+)
func printAll(_ items: any Greetable)any - existential type
extension Array where Element: ComparableConstrained extension
Equatable, Comparable, Hashable, CodableCommon standard protocols
Codable = Encodable & DecodableCodable for JSON encoding/decoding

Error Handling

enum AppError: Error { case notFound; case invalid(String) }Custom error type
func load() throws -> DataThrowing function
func load() async throws -> DataAsync throwing function
try load()Call throwing function
try? load()Convert throw to Optional - nil on error
try! load()Force try - crashes on error
do { let d = try load() } catch AppError.notFound { } catch { print(error) }do-catch
catch let e as AppErrorCatch and cast to specific error type
Result<Data, Error>Result type - .success or .failure

Concurrency (async/await)

func fetch() async -> DataAsync function
let data = await fetch()Await async result
Task { await doWork() }Unstructured async task
Task.detached { await doWork() }Detached task - no actor context
async let a = fetchA(); async let b = fetchB(); let (x, y) = await (a, b)Concurrent binding
await withTaskGroup(of: Int.self) { group in group.addTask { ... } }Task group - structured concurrency
actor Bank { var balance = 0 }Actor - isolated mutable state
await bank.deposit(100)Cross-actor call - must await
@MainActor func updateUI()Run on main thread
nonisolated func pureCalc()Opt out of actor isolation
AsyncStream<Int>Async sequence - model streams with async/await
for await value in stream { }Consume async sequence