Swift Cheat Sheet

Swift programming language reference — optionals, closures, protocols, generics, SwiftUI basics, and essential iOS development patterns.

Last Updated: July 15, 2025

Swift Basics

FeatureExample
Constantslet name = "Swift"
Variablesvar count = 0
Type annotationlet score: Double = 95.5
String interpolation"Hello, \(name)"
Arraysvar items = [1, 2, 3]; items.append(4)

Optionals

PatternExample
Optional declarationvar name: String? (may be nil)
Optional bindingif let name = name { print(name) }
Guard letguard let name = name else { return }
Nil coalescinglet display = name ?? "Unknown"

Closures

SyntaxExample
Full{ (a: Int, b: Int) -> Int in return a + b }
Shorthand{ $0 + $1 }
Trailingarray.map { $0 * 2 }

SwiftUI Quick Start

ElementCode
TextText("Hello, World!")
ButtonButton("Tap") { action() }
VStackVStack { Text("A") Text("B") }
State@State private var count = 0
Pro Tip: Force-unwrapping optionals with ! is a code smell. Use if let, guard let, or nil coalescing (??) instead. A crash from force-unwrapping nil is the #1 Swift runtime error in production apps.
← Back to Programming Languages | Browse all categories | View all cheat sheets