Skip to content
Tutorials Center
My learning

Topics

Lesson 46 of 46 ยท Practice and Interview

iOS and SwiftUI Cheat Sheet

A one-page SwiftUI quick reference: property wrapper chooser, layout and modifier cheat sheet, navigation and presentation snippets, Xcode shortcuts and commands.

This is the page to keep open while you build. It does not teach from scratch; each block links to the lesson that explains the idea in depth. Everything here is a quick reference, so the real SwiftUI snippets are read-only (they need Xcode). Two small runnable stand-ins at the end turn the two most common "which one do I use?" questions into code you can play with.

The four questions

Who owns it? Exactly one view or model.
Who sizes it? Parent proposes, child chooses.
Where am I? Navigation is an array of values.
What changed? Identity decides what is the same view.
1 / 2

Property wrapper chooser

You need Use Notes
Local, simple value owned by one view @State private var Value types; reset when the view's identity changes
Edit a parent's value in a child @Binding var Pass with $value; no storage of its own
Own an observable model in a view @State private var model = Model() Model is a class marked @Observable
Read an observable model from a parent plain let / var property Tracking happens automatically
Create bindings into an observable model @Bindable var model Gives $model.name
Shared model or service from an ancestor @Environment(Model.self) Inject with .environment(model)
System values (color scheme, dismiss, locale) @Environment(\.colorScheme) Key path form
Small persisted setting @AppStorage("key") Backed by UserDefaults
Per-scene UI state restoration @SceneStorage("key") Restored with the scene
Keyboard focus @FocusState Bool or enum
Database rows (SwiftData) @Query Needs a modelContainer
Code that touches the UI @MainActor On view models and UI services

Details: @State and @Binding, @Observable, choosing the right wrapper.

Swift
@Observable final class Cart { var items: [Item] = [] }

struct Shop: View {
    @State private var cart = Cart()          // owner
    var body: some View {
        CartButton().environment(cart)        // inject
    }
}

struct CartButton: View {
    @Environment(Cart.self) private var cart  // reader
    var body: some View { Text("\(cart.items.count) items") }
}

Layout quick reference

Goal Code
Stack vertically / horizontally / overlapping VStack, HStack, ZStack
Alignment and spacing VStack(alignment: .leading, spacing: 8)
Push views apart Spacer()
Fill available width .frame(maxWidth: .infinity)
Fixed size .frame(width: 120, height: 44)
Keep ideal size, do not shrink .fixedSize()
Prefer one view when space is short .layoutPriority(1)
Pick the first layout that fits ViewThatFits { wide; narrow }
Scroll content ScrollView { ... }
Long lists, loaded lazily List, LazyVStack inside ScrollView
Adaptive grid LazyVGrid(columns: [GridItem(.adaptive(minimum: 100))])
Aligned table-like grid Grid { GridRow { ... } }
Respect or ignore safe areas .ignoresSafeArea() (use sparingly)
Measure available space GeometryReader { proxy in ... }

Explained in stacks and spacers and how layout works. The rule behind all of it: the parent proposes, the child chooses, the parent places.

Modifier order rules of thumb

  • Read modifier chains from the inside out: each one wraps the view above it.
  • padding then background: the background includes the padding. background then padding: it does not.
  • frame then background: the background fills the frame.
  • clipShape or cornerRadius must come after background or overlay to clip them.
  • Put font, foregroundStyle and environment-style modifiers anywhere on a container: they flow down to children.
  • Layout modifiers (frame, padding, offset) change geometry; opacity, foregroundStyle and font do not.

More in view modifiers and their order.

Swift
// Value-based navigation with a path you control
@State private var path: [Route] = []

NavigationStack(path: $path) {
    List(items) { item in
        NavigationLink(item.title, value: Route.detail(item.id))
    }
    .navigationDestination(for: Route.self) { route in
        switch route {
        case .detail(let id): DetailView(id: id)
        case .settings: SettingsView()
        }
    }
    .navigationTitle("Items")
}
// path.append(.settings)   push        path.removeLast()  pop       path = []  go to root
Swift
// Tabs
TabView {
    Tab("Home", systemImage: "house") { HomeView() }
    Tab("Search", systemImage: "magnifyingglass") { SearchView() }
}

// Sheet and alert driven by state
.sheet(isPresented: $showSheet) { EditView() }
.sheet(item: $selectedItem) { item in DetailSheet(item: item) }
.alert("Delete this item?", isPresented: $confirming) {
    Button("Delete", role: .destructive) { delete() }
    Button("Cancel", role: .cancel) { }
}
.confirmationDialog("Share", isPresented: $sharing) { /* actions */ }

// Dismiss from inside a presented view
@Environment(\.dismiss) private var dismiss
Swift
// Deep links
.onOpenURL { url in
    if let newPath = router.path(for: url) { path = newPath }
}

See NavigationStack, tabs, sheets and alerts and deep links.

Lists, async work and lifecycle

Swift
List {
    ForEach(items) { item in Text(item.title) }
        .onDelete { indexSet in items.remove(atOffsets: indexSet) }
}
.refreshable { await reload() }
.task { await load() }                       // runs on appear, cancelled on disappear
.onChange(of: query) { oldValue, newValue in search(newValue) }
Event Modifier
View appears / disappears .onAppear, .onDisappear
Async work tied to the view .task, .task(id: value)
A value changed .onChange(of:)
App moves to background @Environment(\.scenePhase)
Pull to refresh .refreshable

Networking and persistence snippets

Swift
let (data, response) = try await URLSession.shared.data(from: url)
guard (response as? HTTPURLResponse)?.statusCode == 200 else { throw APIError.badStatus }
let forecast = try JSONDecoder().decode(Forecast.self, from: data)
Swift
// SwiftData
@Model final class Note { var title: String; var created = Date.now
    init(title: String) { self.title = title } }

WindowGroup { ContentView() }.modelContainer(for: Note.self)

@Query(sort: \Note.created, order: .reverse) private var notes: [Note]
@Environment(\.modelContext) private var context   // context.insert(note), context.delete(note)

Related lessons: Codable and JSON, URLSession, SwiftData.

Xcode shortcuts

Action Shortcut
Build / Run / Stop Cmd+B / Cmd+R / Cmd+.
Run tests Cmd+U
Clean build folder Shift+Cmd+K
Open Quickly (find any file or symbol) Shift+Cmd+O
Comment / uncomment lines Cmd+/
Re-indent selection Ctrl+I
Show or hide the preview canvas Option+Cmd+Return
Resume previews Option+Cmd+P
Show the library (views, modifiers) Shift+Cmd+L

Command-line quick list

Terminal
xcode-select -p                                   # which Xcode is active
xcodebuild -list                                  # schemes and targets in the project
xcrun simctl list devices                         # available simulators
xcrun simctl boot "<device name>"                 # start one
xcrun simctl openurl booted "myapp://item/42"     # test a deep link
xcrun simctl io booted screenshot shot.png        # screenshot of the booted simulator
xcodebuild test -scheme MyApp -destination 'platform=iOS Simulator,name=<device name>'

Replace <device name> with a name shown by simctl list devices; available names change with each Xcode release.

Release checklist (short)

  1. Bundle id, version and build number set; build number increments on every upload.
  2. Capabilities and entitlements match the features you use.
  3. Privacy manifest and the App Store privacy answers are accurate.
  4. Release build tested on a real device; TestFlight build installed by at least one tester.
  5. Screenshots, description and review notes ready.

Full walkthrough: signing, TestFlight and App Store release.

Two stand-ins to play with

The first one encodes the property wrapper chooser as a function. Change the facts about a value and watch the answer change.

Swift Property wrapper chooser

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The second picks the right presentation style for a situation, a decision people regularly get wrong.

Swift Which presentation style?

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. A child view must edit a Bool that a parent owns. Which wrapper does the child use?

    @Binding gives the child a getter and setter into the parent's state, without a second copy.
  2. 2. .background(.red).padding(12) versus .padding(12).background(.red): which one paints the padding area red?

    Background fills the size the view has when it is applied. In the second form, padding has already been added.
  3. 3. Which modifier runs async work when a view appears and cancels it when the view goes away?

    .task is tied to the view's lifetime, so its work is cancelled automatically.
  4. 4. What drives a NavigationStack(path:) so you can navigate from code?

    The path binding holds the pushed values. Appending to it pushes, removing the last element pops.

Summary

  • One owner per value: @State owns, @Binding borrows, @Environment injects, @AppStorage persists.
  • Layout is a negotiation; modifiers wrap views from the inside out.
  • Navigation is data: a path array you can append to, trim or replace from a deep link.
  • .task for async work tied to a view, .onChange for reactions, @MainActor for UI code.
  • Keep the Xcode shortcuts and simctl commands handy to iterate faster.

This is the end of the course. Go back to the practice exercises or build an expense tracker on your own.