Swift & iOS

A practical guide to SwiftUI state ownership, @Binding, Observation, navigation, lifecycle, layout, and SwiftData.

~28 min reading
Suggest content

Modern SwiftUI Engineering Reference

🟪 Syntax · 🟦 Types/APIs · 🟩 Correct pattern · 🟥 Bug · 🟨 Gotcha · 🧠 Explanation

For code-review practice on UI controls, state ownership, identity, navigation, task lifetime, and stale results, use the advanced Swift and SwiftUI questionnaire. Attempt its prompts before opening the separate answer key.

Current baseline

This guide targets current SwiftUI code with the Swift 6.4 compiler and iOS 27 SDK. Your app's deployment target still determines which APIs you can call without availability checks. Observation and SwiftData require iOS 17; NavigationStack requires iOS 16. Use #available or keep a compatible older implementation when supporting earlier systems.

State ownership in one table

Wrapper/APIOwns storage?Main use
@StateYes, for view-local value or reference stateSelection, form values, presentation state, or an owned @Observable model
@BindingNoChild reads/writes a value owned by a parent
@ObservableModel declaration macroMakes properties of a reference type observable
@BindableNoCreates bindings to properties on an @Observable model
@EnvironmentNoReads a system value or dependency injected into the view hierarchy
@StateObjectYes, for ObservableObjectOwns a legacy ObservableObject reference
@ObservedObjectNoObserves an injected legacy ObservableObject
@EnvironmentObjectNoReads a shared legacy ObservableObject from the environment

Modern Observation model

SWIFT
import SwiftUI
import Observation
​
@MainActor
@Observable
final class ProfileModel {
    var name = "Taylor"
    var isSaving = false
​
    func save() async {
        isSaving = true
        defer { isSaving = false }
        // Call the service and update model state.
    }
}
​
struct ProfileScreen: View {
    @State private var model = ProfileModel()
​
    var body: some View {
        @Bindable var model = model
​
        Form {
            TextField("Name", text: $model.name)
            Button("Save") {
                Task { await model.save() }
            }
            .disabled(model.isSaving)
        }
    }
}

SwiftUI tracks observable properties that a view reads. @Bindable is for forming bindings, not for ownership. Keep a model's state on the main actor when it directly drives UI and is mutated by UI actions.

Pass data down and actions up

Use a Binding when the child edits a value owned by its parent, pass a model when the child needs a meaningful set of operations, and pass a closure for one focused action. The full question-by-question explanation and declaration examples are in State Management → @Binding.

Environment dependencies

SWIFT
@Observable
final class Session {
    var displayName = "Guest"
}
​
@main
struct ExampleApp: App {
    @State private var session = Session()
​
    var body: some Scene {
        WindowGroup {
            HomeScreen()
                .environment(session)
        }
    }
}
​
struct HomeScreen: View {
    @Environment(Session.self) private var session
​
    var body: some View {
        Text("Hello, \(session.displayName)")
    }
}

Use the environment for genuinely shared app/session dependencies. Use initializer injection when a dependency is feature-specific or should be obvious at the call site. Missing required environment values are configuration errors, so install them at the app or feature root and make previews provide them too.

State Management

@State

What does State own in a SwiftUI view?

Short answer: State gives a SwiftUI view persistent storage associated with its identity, so ordinary view reconstruction does not discard the value. Use it for view-owned local data or an Observable model created at that ownership boundary. An intentional change of view identity can still recreate the state.

Detailed explanation:

@State gives SwiftUI-managed storage owned by a view identity. Use it for small local values or for an @Observable model that this view creates and owns. SwiftUI preserves that storage across ordinary view-value recreation while the view identity remains stable; changing identity can reset it.

SWIFT
struct CounterView: View {
    @State private var count = 0
​
    var body: some View {
        Button("Count: \(count)") { count += 1 }
    }
}

Do not use @State as a global store or recreate long-lived reference state in a transient child. For an injected editable value, use @Binding instead.

@Binding

How does Binding connect a child to parent-owned state?

Short answer: Binding supplies read and write access to a value whose storage is owned elsewhere. When a child edits through the binding, it updates the same source of truth that the parent reads. It does not create a second stored value or take ownership of the parent's state.

Detailed explanation:

Explanation: @Binding gives a view read/write access to a value whose storage is owned elsewhere. It is a connection to the source of truth, not a second owned copy.

The parent owns the value with @State (or another binding-capable source) and passes the projected binding using $. The child declares @Binding; reads use the wrapped value, and writes go back through the binding to the owner. This lets SwiftUI update the views that depend on the changed state.

🟦 Illustrative example:

SWIFT
import SwiftUI
​
struct DraftTitleField: View {
    @Binding var title: String
    var body: some View { TextField("Draft title", text: $title) }
}
struct DraftScreen: View {
    @State private var title = ""
    var body: some View { DraftTitleField(title: $title) }
}

🧠 Typing updates the screen-owned storage through the child binding. The child does not create a second independent title, so both views observe the same source of truth.

How do you pass editable state into a child view?

Short answer: The owner passes a binding to its state, and the child declares a Binding property for that editable input. Reads and writes then reach the owner's stored value. If the child defines a custom initializer, it should receive and forward the binding itself rather than creating unrelated local storage.

Detailed explanation:

SWIFT
import SwiftUI
​
struct ParentView: View {
    @State private var username = ""
​
    var body: some View {
        UsernameEditor(username: $username)
    }
}
​
struct UsernameEditor: View {
    @Binding var username: String
​
    var body: some View {
        TextField("Username", text: $username)
    }
}

The initializer receives Binding<String> at the call site as username: $username. With a custom initializer, assign the wrapper storage (_username = username); do not try to construct a protocol-like Binding with Binding().

When should you create a custom Binding?

Short answer: Create a custom binding when editable access must adapt an existing source of truth, such as applying a deliberate conversion or validation rule. Its getter reads that source and its setter updates the same owner. Prefer a direct projected binding when adaptation is unnecessary, because a custom binding does not provide storage by itself.

Detailed explanation:

Use Binding(get:set:) to adapt an existing source of truth or expose a derived editable value. Keep both closures connected to the same owner and make the setter's behavior explicit.

SWIFT
struct SettingsToggle: View {
    @State private var isEnabled = false
​
    var body: some View {
        let enabled = Binding<Bool>(
            get: { isEnabled },
            set: { isEnabled = $0 }
        )
        Toggle("Enabled", isOn: enabled)
    }
}

Prefer a direct projected binding such as $username when possible. A custom binding is an adapter, not storage; it does not make a temporary value persistent or establish ownership.

When does a child view need a Binding?

Short answer: Use a Binding when the child needs to both display and edit a particular value owned elsewhere. Pass an ordinary value for read-only input or a callback when the child only reports an action. This gives the child the capability it actually needs without granting unnecessary access to an entire model.

Detailed explanation:

Use it when the child both displays and edits a specific piece of parent-owned state, such as a text field, toggle, selection, or presentation flag. Use a plain let when the child only reads a value, a closure when it only reports an action, and a model when the child needs cohesive behavior or several related operations.

🟦 Illustrative example:

SWIFT
import SwiftUI
​
struct SettingsRow: View {
    let title: String
    @Binding var enabled: Bool
    let showDetails: () -> Void
    var body: some View {
        Toggle(title, isOn: $enabled)
        Button("Details", action: showDetails)
    }
}

🧠 A plain value supplies read-only text, a binding supplies editable state, and a closure reports an action. These different contracts avoid granting a child write access to an entire parent model merely to toggle one setting.

How do State and Binding divide ownership?

Short answer: State is the owning view's storage, while Binding is editable access to storage owned elsewhere. A parent can keep one value in State and let a child edit it through a Binding. Giving that child a separate State copy instead can create two values that drift apart.

Detailed explanation:

@State owns SwiftUI-managed storage scoped to a view identity. @Binding provides read/write access to storage owned elsewhere, so a child can edit the parent's value without creating a separate source of truth.

@State@Binding
Owns storage?Yes, scoped to the view identity.No; refers to storage owned elsewhere.
Typical roleSource of truth in the owning view.Editable access passed to a child.
Projection$value creates a binding.The property is already a binding; $value can pass its projected wrapper onward.

Do not add @State to a child merely to make an input editable; that creates independent child state that can diverge from the parent.

🟦 Illustrative example:

SWIFT
import SwiftUI
​
struct SearchOwner: View {
    @State private var query = ""
    var body: some View { SearchInput(query: $query) }
}
struct SearchInput: View {
    @Binding var query: String
    var body: some View { TextField("Search", text: $query) }
}

🧠 Only SearchOwner creates storage. Replacing the child binding with @State initialized from the input would create a snapshot whose later edits can diverge from the owner.

When should you use Binding rather than Bindable?

Short answer: Use Binding when a view receives editable access to a value, such as a parent-owned text field or toggle. Use Bindable with an Observable reference model when the view needs to create bindings to that model's properties. Neither wrapper establishes ownership of the underlying model; that belongs at the appropriate owner boundary.

Detailed explanation:

@Binding is a property wrapper for a value binding supplied from outside, commonly a parent-owned scalar or a binding already created elsewhere. @Bindable works with an @Observable reference model and lets a view form bindings to that model's mutable properties. Neither wrapper owns the underlying model. Use @State at the owning boundary when the view creates the model.

🟦 Illustrative example:

SWIFT
import SwiftUI
import Observation
​
@Observable
final class ProfileDraft {
    var name = ""
}
struct ProfileEditor: View {
    @Bindable var draft: ProfileDraft
    var body: some View { TextField("Name", text: $draft.name) }
}
struct ProfileOwner: View {
    @State private var draft = ProfileDraft()
    var body: some View { ProfileEditor(draft: draft) }
}

🧠 For iOS 17+ Observation, @State owns this model identity and @Bindable exposes property bindings without owning a new model. A child editing a supplied Binding<String> instead would use @Binding; the wrappers address different input shapes. Apple: Bindable.

Can you construct a Binding yourself?

Short answer: Yes, a custom binding can provide a getter and setter connected to a real, sufficiently long-lived source of truth, and an initializer can also forward an existing binding. Constant bindings are useful for fixed preview inputs. Constructing a binding does not itself persist, own, or synchronize a temporary value.

Detailed explanation:

Yes, with a meaningful getter and setter, for example Binding(get:set:), or by forwarding an existing binding in a custom initializer. SwiftUI also offers constant bindings for previews or read-only controls. Do not fabricate a binding around a local temporary variable: the source must outlive the view and remain the real source of truth.

🟦 Illustrative example:

SWIFT
import SwiftUI
​
struct VolumeEditor: View {
    @State private var volume = 0.5
    var body: some View {
        let bounded = Binding<Double>(
            get: { volume },
            set: { volume = min(1, max(0, $0)) }
        )
        Slider(value: bounded, in: 0...1)
    }
}

🧠 The getter and setter refer to the same view-owned storage, and the setter states its clamping policy. Prefer $volume when adaptation is unnecessary; a custom binding does not itself store, persist, or synchronize the value.

Common @Binding mistakes

  • Passing username instead of $username when the child needs a binding.
  • Declaring child state with @State and accidentally creating a second source of truth.
  • Using a binding for a one-way value or action when a let or closure is clearer.
  • Capturing short-lived or unsynchronized mutable data in a custom getter/setter.
  • Treating @Binding as an observable model, persistence mechanism, or cross-thread synchronization tool.

View identity and rendering

  • A SwiftUI View is a value describing UI. SwiftUI can recreate that value often; do not start network requests or create long-lived side effects in body.
  • @State storage is associated with a view's identity. Changing .id(...) creates a new identity and can reset state.
  • In ForEach and List, use stable identities (Identifiable or stable IDs), never array offsets for mutable server data.
  • Keep body declarative and small. Extract meaningful reusable UI into a View type; use @ViewBuilder for small conditional content slots.
  • Modifiers wrap views. Modifier order matters: for example, padding before a background differs from background before padding.
  • Avoid AnyView unless type erasure is truly needed; conditionals and @ViewBuilder already support many different child branches.
SWIFT
struct ProductRow: View {
    let product: Product
​
    var body: some View {
        HStack {
            Text(product.name)
            Spacer()
            Text(product.price, format: .currency(code: "USD"))
        }
        .padding(.vertical, 8)
    }
}
​
struct ProductList: View {
    let products: [Product]
​
    var body: some View {
        List(products) { product in
            ProductRow(product: product)
        }
    }
}

Lifecycle work and cancellation

Use .task for asynchronous work tied to a view's presence. Use .task(id:) for work that must restart when an input changes, such as search. SwiftUI can cancel the task when the view disappears or the ID changes; cancellation is cooperative, so called code should honor cancellation too.

SWIFT
struct SearchScreen: View {
    @State private var query = ""
    @State private var results: [SearchResult] = []
    let search: (String) async throws -> [SearchResult]
​
    var body: some View {
        List(results) { result in
            Text(result.title)
        }
        .searchable(text: $query)
        .task(id: query) {
            let normalized = query.trimmingCharacters(in: .whitespacesAndNewlines)
            guard !normalized.isEmpty else {
                results = []
                return
            }
​
            do {
                try await Task.sleep(for: .milliseconds(300))
                try Task.checkCancellation()
                results = try await search(normalized)
            } catch is CancellationError {
                // A newer query owns the screen now.
            } catch {
                results = []
            }
        }
    }
}

For a real screen, expose loading, empty, content, and failure as explicit UI states; don't treat every error as an empty result. Put request policy in a model/service, not in a large view body.

State-driven navigation

NavigationStack supports typed values and a path that the app can save, inspect, or update. Keep route values small and stable—usually IDs—not full mutable domain models.

SWIFT
enum Route: Hashable, Codable {
    case product(UUID)
    case account
}
​
struct CatalogNavigation: View {
    @State private var path: [Route] = []
    let products: [Product]
​
    var body: some View {
        NavigationStack(path: $path) {
            List(products) { product in
                NavigationLink(product.name, value: Route.product(product.id))
            }
            .navigationTitle("Catalog")
            .navigationDestination(for: Route.self) { route in
                switch route {
                case .product(let id):
                    ProductDetailsScreen(productID: id)
                case .account:
                    AccountScreen()
                }
            }
        }
    }
}

Use NavigationSplitView when the interface has coordinated columns, such as a sidebar and detail view. Avoid new NavigationView code for stack navigation. Deep links should validate route input and resolve IDs through the data layer.

Layout, accessibility, and platform fit

  • Use VStack, HStack, and ZStack for simple composition; use LazyVStack/LazyVGrid for large scrolling content.
  • Let text wrap and respect Dynamic Type. Avoid fixed heights for text-heavy controls.
  • Add meaningful labels and hints to custom controls; maintain sufficient hit targets and contrast.
  • Prefer semantic system colors, materials, and platform controls so the system appearance adapts. Test both light and dark appearances and different size classes.
  • Respect safe areas deliberately. Use safeAreaInset for persistent controls that should reserve space.
  • Follow the current platform design language rather than drawing a system surface by hand when a native control already provides it.

SwiftData in a SwiftUI feature

SWIFT
import SwiftData
​
@Model
final class SavedArticle {
    @Attribute(.unique) var id: UUID
    var title: String
    var savedAt: Date
​
    init(id: UUID = UUID(), title: String, savedAt: Date = .now) {
        self.id = id
        self.title = title
        self.savedAt = savedAt
    }
}
​
struct SavedArticlesScreen: View {
    @Query(sort: \SavedArticle.savedAt, order: .reverse)
    private var articles: [SavedArticle]
​
    var body: some View {
        List(articles) { article in
            Text(article.title)
        }
    }
}

Install .modelContainer(for:) at the app or feature root. @Query is a SwiftUI-facing fetch; use ModelContext and FetchDescriptor for imperative fetches and operations outside a view. Plan schema migration and test persistence behavior instead of assuming a model edit is harmless.

Previews and availability

SWIFT
#Preview("Profile") {
    ProfileScreen()
}
​
if #available(iOS 17, *) {
    // Observation or SwiftData path.
} else {
    // Compatibility path for an older deployment target.
}

Make previews deterministic: inject sample models and fake services, avoid production network calls, and keep preview data representative of empty, loading, error, and content states.

Quick migration map from older SwiftUI

Older patternModern direction
ObservableObject + @Published for new iOS 17+ apps@Observable model; @State for owner; @Bindable for edits
@StateObject / @ObservedObjectKeep for legacy ObservableObject code; don't wrap an @Observable model with them
NavigationView stackNavigationStack; use NavigationSplitView for columns
Networking in onAppear.task / .task(id:) with cancellation-aware async work
Big view with nested conditionalsExplicit screen state and small composed views

References