contentintech

iOS with Swift Cheatsheet

Quick reference for iOS with Swift — Swift syntax and optionals, SwiftUI views and layout stacks, state property wrappers, navigation, async/await networking, and common view modifiers.

SwiftUISwiftStateConcurrency
NotesCheatsheet

Swift Syntax Basics

Declarations & Types

let name = "Ada"          // constant, inferred
var count: Int = 0        // variable, explicit
count += 1

let list: [Int] = [1, 2, 3]        // Array<Int>
let map: [String: Int] = ["a": 1]  // Dictionary
let text = "count = \(count)"      // interpolation

Struct / Enum / Protocol

struct Task: Identifiable, Codable {
    let id: UUID
    var title: String
    var done = false
}

enum Priority: String, CaseIterable { case low, medium, high }
enum Result_ { case ok([Task]); case fail(Error) }   // associated values

protocol Repository { func fetch() async throws -> [Task] }

Closures & Higher-Order

let sorted = nums.sorted { $0 < $1 }
let doubled = nums.map { $0 * 2 }
let evens = nums.filter { $0 % 2 == 0 }
let sum = nums.reduce(0, +)

Optionals

var nick: String? = nil          // optional

if let nick { use(nick) }        // optional binding
guard let nick else { return }   // early exit

let shown = nick ?? "Guest"      // nil-coalescing
let n = nick?.count ?? 0         // optional chaining
let forced = nick!               // force unwrap (crashes if nil)

SwiftUI Views

struct MyView: View {
    var body: some View {
        Text("Hello")
    }
}
#Preview { MyView() }

Text("Title").font(.title).bold()
Image(systemName: "star.fill")
Button("Tap") { action() }
Toggle("On", isOn: $flag)
TextField("Name", text: $name)
Label("Home", systemImage: "house")
ProgressView()

Layout Stacks

VStack(spacing: 8) { ... }        // vertical
HStack(alignment: .top) { ... }   // horizontal
ZStack { ... }                    // overlapping (z-axis)
LazyVStack { ... }                // lazy scrolling content
Spacer()                          // flexible gap
Grid { GridRow { A; B } }         // 2D grid
ScrollView { VStack { ... } }

State Property Wrappers

WrapperUse for
@StateView-local value / owned model
@BindingTwo-way ref to external state
@ObservableReference-type model class
@EnvironmentInjected shared values
@State private var count = 0
Button("+") { count += 1 }
Toggle("On", isOn: $flag)        // $ = Binding projection

@Binding var value: Int          // child receives binding

import Observation
@Observable final class Model { var items: [Task] = [] }
@State private var model = Model()

@Environment(\.dismiss) private var dismiss

Lists & Navigation

List(tasks) { task in Text(task.title) }

List {
    ForEach(tasks) { Text($0.title) }
        .onDelete { tasks.remove(atOffsets: $0) }
}

NavigationStack {
    List(tasks) { t in
        NavigationLink(t.title, value: t)
    }
    .navigationTitle("Tasks")
    .navigationDestination(for: Task.self) { t in
        DetailView(task: t)
    }
}

Async/await + Networking

func fetch() async throws -> [Post] {
    let url = URL(string: "https://api.example.com/posts")!
    let (data, resp) = try await URLSession.shared.data(from: url)
    guard (resp as? HTTPURLResponse)?.statusCode == 200
    else { throw URLError(.badServerResponse) }
    return try JSONDecoder().decode([Post].self, from: data)
}

// Concurrent work
async let a = fetch()
async let b = fetch()
let all = try await a + b

// Kick off from a view (auto-cancels)
.task { await model.load() }

@MainActor @Observable final class VM {
    var posts: [Post] = []
    func load() async { posts = (try? await fetch()) ?? [] }
}

View Modifiers

ModifierEffect
.padding()Add inset spacing
.frame(width:height:)Fixed / flexible size
.foregroundStyle(_)Text / icon color
.background(_)Fill behind the view
.font(_)Text style
.clipShape(_)Mask to a shape
.onTapGestureHandle taps
.disabled(_)Turn interaction off
.sheet(isPresented:)Present a modal
.overlay / .safeAreaInsetLayer views on top

Section navigation