Cheatsheet
Swift cheatsheet: syntax, types, control flow, SwiftUI, async/await, error handling.
Swift — cheatsheet
EXAMPLE
// ===== Variables + types =====
let pi = 3.14
var count = 0
let name: String = "Alex"
let maybe: String? = nil
let forced = maybe! // crash if nil — use sparingly
// Collections:
let nums = [1, 2, 3]
let ages: [String: Int] = ["Alex": 30]
let tags: Set<String> = ["vip", "beta"]
// ===== Control flow =====
if let value = maybe { print(value) }
guard let value = maybe else { return }
for n in 1...10 { print(n) }
while count < 5 { count += 1 }
switch n {
case 0: print("zero")
case 1...9: print("small")
default: print("big")
}
// ===== Functions =====
func greet(_ name: String, with greeting: String = "Hello") -> String {
"\(greeting), \(name)"
}
greet("Alex")
greet("Sam", with: "Hi")
// ===== Structs + classes =====
struct Point { var x: Double; var y: Double } // value type
class Counter { var n = 0 } // reference type
// ===== Records via struct + Codable =====
struct User: Codable {
let id: UUID
let email: String
let name: String
}
// ===== Protocols =====
protocol Describable { var description: String { get } }
extension User: Describable {
var description: String { name }
}
// ===== Generics =====
func first<T>(_ xs: [T]) -> T? { xs.first }
// ===== Enums (with associated values) =====
enum Result<T> {
case success(T)
case failure(Error)
}
// ===== Optionals + chaining =====
let len = user?.profile?.bio?.count ?? 0
// ===== async / await =====
func fetch(_ url: URL) async throws -> Data {
let (data, _) = try await URLSession.shared.data(from: url)
return data
}
// Parallel:
async let a = fetch(url1)
async let b = fetch(url2)
let (da, db) = try await (a, b)
// ===== Error handling =====
enum AppError: Error { case notFound }
do {
let user = try await loadUser()
} catch AppError.notFound {
print("not found")
} catch {
print(error)
}
// ===== SwiftUI =====
struct CounterView: View {
@State private var count = 0
var body: some View {
VStack {
Text("\(count)").font(.title)
Button("+1") { count += 1 }
}
}
}
// State management:
// @State local to view
// @Binding passed-down 2-way
// @ObservedObject view-supplied
// @StateObject view-owned
// @EnvironmentObject shared across view hierarchy
// @AppStorage UserDefaults-backed
// @SceneStorage per-scene
// ===== Lists =====
NavigationStack {
List(users) { user in
NavigationLink(user.name, destination: ProfileView(user: user))
}
.navigationTitle("Users")
}
// ===== Forms =====
Form {
TextField("Email", text: $email)
SecureField("Password", text: $password)
Toggle("Remember me", isOn: $remember)
}
// ===== Modifiers =====
.padding()
.background(Color.blue)
.cornerRadius(8)
.shadow(radius: 4)
.frame(width: 200, height: 100)
// ===== Patterns =====
// - struct + value semantics by default
// - Optional types in signatures
// - async / await over completion handlers
// - SwiftUI declarative composition
// - Codable for JSON
// ===== Pitfalls =====
// - Force-unwrap (!) -> crashes
// - Capturing self in closures (use [weak self])
// - Massive view controllers (UIKit)
// - Mixing Combine + async/await without a strategy
Why it matters
Swift cheatsheet: optionals, structs vs classes, protocols, generics, async/await, SwiftUI state, error handling. Pin this during any iOS sprint and the common pieces stay close to hand.
Tip: Tweak the snippet with Try it Yourself », then sit the quiz at the bottom of the page.
Discussion
Loading…