Skip to main content

Mobile development · Intermediate · 24 min

Manage state in SwiftUI with @State, @Binding and @Observable

By Padding · Updated 18 Nov 2026
Ubuntu 26.04 (swift:6.4 image) · Swift 6.4.3 · Xcode 27.1 for the SwiftUI views

You will build a mobile data budget app whose @MainActor @Observable model lives in a tested Swift package, then wire it into SwiftUI with @State, @Binding, @Bindable, @Environment and an async load in .task.

On this page

Every piece of state in a SwiftUI app has one owner. When you know who that owner is, the property wrapper almost picks itself: a view that owns a small value uses @State, a child that edits someone else's value takes a @Binding, and data that several screens share lives in an @Observable class that is handed down through the environment. Most state bugs in SwiftUI (a text field that resets, a screen that shows old numbers, a list that reloads on every redraw) come from two owners fighting over one value, or from a model that is created again each time a view's init runs.

In this tutorial you build Data Budget, a small app for people on prepaid mobile data. It shows the bundles you have bought, how many megabytes each has left, lets you log what you used and warns you when the total drops below a limit you set. Prepaid bundles are how most people pay for mobile data across much of Africa and elsewhere, and a few hundred megabytes can decide whether a call goes through, so the numbers have to be right.

You split the work in two:

  • DataBudgetKit, a Swift package that holds the model and its rules: a @MainActor @Observable class, an async load from a data source, and usage checks. You build and test it with swift build and swift test. The Observation framework ships with the Swift toolchain, so this part runs on Linux as well as on a Mac.
  • The SwiftUI views, in an Xcode 27.1 app project, which use the package. These need a Mac.

Everything was written for Swift 6.4.3. The package uses the Swift 6 language mode, so the compiler checks for data races.

Step 1 · Create the model package

Work in a throwaway folder. Create a library package, then remove the generated placeholder files so you can lay out your own:

Bash
mkdir -p ~/databudget-demo
cd ~/databudget-demo
swift package init --type library --name DataBudgetKit
rm -r Sources Tests
mkdir -p Sources/DataBudgetKit Tests/DataBudgetKitTests

Replace Package.swift with this manifest:

Bash
cd ~/databudget-demo
cat > Package.swift <<'SWIFT'
// swift-tools-version: 6.4
import PackageDescription

let package = Package(
    name: "DataBudgetKit",
    platforms: [.iOS(.v18), .macOS(.v15)],
    products: [
        .library(name: "DataBudgetKit", targets: ["DataBudgetKit"]),
    ],
    targets: [
        .target(name: "DataBudgetKit"),
        .testTarget(name: "DataBudgetKitTests", dependencies: ["DataBudgetKit"]),
    ]
)
SWIFT

swift-tools-version: 6.4 turns on the Swift 6 language mode for every target, which makes data-race checks errors rather than warnings. platforms matters only on Apple systems: Observation needs iOS 17 or macOS 14, and the tests later use Mutex, which needs iOS 18 or macOS 15. On Linux the line is ignored.

Check it worked

ls ~/databudget-demo shows Package.swift, Sources and Tests, and swift package dump-package (run inside the folder) prints the manifest as JSON that names both targets, DataBudgetKit and DataBudgetKitTests. Use dump-package rather than swift package describe here: describe resolves the real targets, and with both folders still empty it stops with target 'DataBudgetKit' referenced in product 'DataBudgetKit' is empty.

Step 2 · Write the value types and the data source

The bundles themselves are plain structs. Structs are copied, not shared, so they are safe to pass between threads, and marking them Sendable tells the compiler so. The data source is a protocol, so the app can load from a server while the tests use a stand-in that answers instantly.

Bash
cd ~/databudget-demo
cat > Sources/DataBudgetKit/DataBundle.swift <<'SWIFT'
public struct DataBundle: Identifiable, Equatable, Sendable {
    public let id: String
    public var name: String
    public var sizeMB: Int
    public var usedMB: Int

    public init(id: String, name: String, sizeMB: Int, usedMB: Int = 0) {
        self.id = id
        self.name = name
        self.sizeMB = sizeMB
        self.usedMB = usedMB
    }

    public var remainingMB: Int { max(sizeMB - usedMB, 0) }
}

public enum LoadState: Equatable, Sendable {
    case idle
    case loading
    case loaded
    case failed(String)
}

public enum UsageError: Error, Equatable {
    case notPositive
    case unknownBundle
    case moreThanRemaining(Int)

    public var message: String {
        switch self {
        case .notPositive: "Enter an amount above 0 MB."
        case .unknownBundle: "That bundle no longer exists."
        case .moreThanRemaining(let left): "Only \(left) MB left on this bundle."
        }
    }
}

public protocol BundleSource: Sendable {
    func fetchBundles() async throws -> [DataBundle]
}

/// Sample data with a short delay, for previews and the first run of the app.
public struct SampleBundleSource: BundleSource {
    public var delay: Duration

    public init(delay: Duration = .milliseconds(400)) {
        self.delay = delay
    }

    public func fetchBundles() async throws -> [DataBundle] {
        try await Task.sleep(for: delay)
        return [
            DataBundle(id: "weekly", name: "Weekly 1.5 GB", sizeMB: 1500, usedMB: 1320),
            DataBundle(id: "night", name: "Night 1 GB", sizeMB: 1000, usedMB: 200),
        ]
    }
}
SWIFT
swift build

remainingMB never goes below zero, even if a provider reports more use than the bundle size. UsageError carries the message the app shows, so the wording lives next to the rule that produces it.

Check it worked

swift build ends with Build complete!. If it reports an error, compare the file with the listing above; a missing public is the usual cause. You will also see a warning that source files for target DataBudgetKitTests should be located under Tests/DataBudgetKitTests. That is expected: the test folder stays empty until the testing step, and the warning goes away once the test file exists.

Step 3 · Write the observable model

Now the class the screens share. Three things are on it:

  • @Observable comes from the Observation framework. It rewrites each stored property so that reading it records "this code depends on this property", and changing it tells exactly those readers. A SwiftUI view that reads totalRemainingMB redraws when bundles changes, and not when lowDataThresholdMB changes unless it reads that too.
  • @MainActor says every property and method runs on the main actor, the same place SwiftUI draws. The compiler then refuses code that touches the model from a background thread.
  • load() is async. The fetch can wait on the network, but the state changes before and after it happen on the main actor.
Bash
cd ~/databudget-demo
cat > Sources/DataBudgetKit/BundleTracker.swift <<'SWIFT'
import Observation

@MainActor
@Observable
public final class BundleTracker {
    public private(set) var bundles: [DataBundle] = []
    public private(set) var loadState: LoadState = .idle
    public var lowDataThresholdMB = 100

    // A `let` is never tracked: it cannot change, so nothing needs telling.
    private let source: any BundleSource

    public init(source: any BundleSource) {
        self.source = source
    }

    public var totalRemainingMB: Int {
        bundles.reduce(0) { $0 + $1.remainingMB }
    }

    public var isRunningLow: Bool {
        loadState == .loaded && totalRemainingMB < lowDataThresholdMB
    }

    public func load() async {
        guard loadState != .loading else { return }
        loadState = .loading
        do {
            bundles = try await source.fetchBundles()
            loadState = .loaded
        } catch is CancellationError {
            loadState = .idle
        } catch {
            loadState = .failed(String(describing: error))
        }
    }

    public func recordUsage(_ megabytes: Int, on id: DataBundle.ID) throws(UsageError) {
        guard megabytes > 0 else { throw .notPositive }
        guard let index = bundles.firstIndex(where: { $0.id == id }) else {
            throw .unknownBundle
        }
        let left = bundles[index].remainingMB
        guard megabytes <= left else { throw .moreThanRemaining(left) }
        bundles[index].usedMB += megabytes
    }
}
SWIFT
swift build

Some choices worth noticing:

  • bundles and loadState are private(set). Views can read them, but only the model's own methods change them, so every rule (no negative amounts, no more than is left) is enforced in one place.
  • lowDataThresholdMB is a plain public var, because it is a setting the person changes directly. Later a settings screen binds a stepper to it.
  • Computed properties such as totalRemainingMB need no extra work. Observation tracks the stored properties they read.
  • The guard at the top of load() stops a second load starting while one is running, for example if a screen appears twice quickly.
  • SwiftUI cancels a .task when its view goes away. Task.sleep and URLSession then throw CancellationError, which is not a real failure, so the model goes back to .idle instead of showing an error.
  • throws(UsageError) is a typed throw: callers know the only error they can get is a UsageError, so they can read error.message without casting.

Check it worked

swift build ends with Build complete! and prints no warnings about concurrency or Sendable. The warning about the empty DataBudgetKitTests target is still expected at this point.

Step 4 · Test the rules and the observation with Swift Testing

The model has no SwiftUI in it, so you can test it like any other Swift code. The tests below check loading, failure, cancellation and the usage rules, and then use withObservationTracking to prove which property changes notify which readers. That is the same mechanism SwiftUI uses to decide what to redraw.

Bash
cd ~/databudget-demo
cat > Tests/DataBudgetKitTests/BundleTrackerTests.swift <<'SWIFT'
import Observation
import Synchronization
import Testing
@testable import DataBudgetKit

enum StubError: Error { case offline }

struct StubSource: BundleSource {
    var result: Result<[DataBundle], StubError>

    func fetchBundles() async throws -> [DataBundle] {
        try result.get()
    }
}

/// Records whether an observation fired. onChange can run on any thread, so it uses a Mutex.
final class ChangeFlag: Sendable {
    private let fired = Mutex(false)
    func fire() { fired.withLock { $0 = true } }
    var didFire: Bool { fired.withLock { $0 } }
}

let twoBundles = [
    DataBundle(id: "a", name: "Daily 500 MB", sizeMB: 500, usedMB: 450),
    DataBundle(id: "b", name: "Social 300 MB", sizeMB: 300, usedMB: 100),
]

@MainActor
func loadedTracker() async -> BundleTracker {
    let tracker = BundleTracker(source: StubSource(result: .success(twoBundles)))
    await tracker.load()
    return tracker
}

@MainActor
struct BundleTrackerTests {
    @Test func loadFillsBundlesAndTotal() async {
        let tracker = await loadedTracker()
        #expect(tracker.loadState == .loaded)
        #expect(tracker.bundles.count == 2)
        #expect(tracker.totalRemainingMB == 250)
        #expect(tracker.isRunningLow == false)
    }

    @Test func failedLoadKeepsTheReason() async {
        let tracker = BundleTracker(source: StubSource(result: .failure(.offline)))
        await tracker.load()
        #expect(tracker.loadState == .failed("offline"))
        #expect(tracker.bundles.isEmpty)
    }

    @Test func cancelledLoadGoesBackToIdle() async {
        let tracker = BundleTracker(source: SampleBundleSource(delay: .seconds(5)))
        let task = Task { await tracker.load() }
        task.cancel()
        await task.value
        #expect(tracker.loadState == .idle)
    }

    @Test func usageRules() async throws {
        let tracker = await loadedTracker()
        #expect(throws: UsageError.notPositive) { try tracker.recordUsage(0, on: "a") }
        #expect(throws: UsageError.unknownBundle) { try tracker.recordUsage(10, on: "zzz") }
        #expect(throws: UsageError.moreThanRemaining(50)) { try tracker.recordUsage(60, on: "a") }

        try tracker.recordUsage(30, on: "a")
        #expect(tracker.bundles[0].remainingMB == 20)
        #expect(tracker.totalRemainingMB == 220)
    }

    @Test func runningLowFollowsTheThreshold() async {
        let tracker = await loadedTracker()
        tracker.lowDataThresholdMB = 300
        #expect(tracker.isRunningLow)
    }

    @Test func thresholdChangeNotifiesWarningReaders() async {
        let tracker = await loadedTracker()
        let flag = ChangeFlag()
        _ = withObservationTracking {
            tracker.isRunningLow
        } onChange: {
            flag.fire()
        }
        tracker.lowDataThresholdMB = 300
        #expect(flag.didFire)
    }

    @Test func usageDoesNotNotifyThresholdReaders() async throws {
        let tracker = await loadedTracker()
        let flag = ChangeFlag()
        _ = withObservationTracking {
            tracker.lowDataThresholdMB
        } onChange: {
            flag.fire()
        }
        try tracker.recordUsage(10, on: "b")
        #expect(flag.didFire == false)
    }
}
SWIFT
swift test 2>&1 | tee /tmp/databudget-test.txt

Marking the whole suite @MainActor means each test runs on the main actor, so it can call the model directly, the same way a view does. The last two tests are the heart of Observation: code that read isRunningLow is told when the threshold changes, because isRunningLow reads it, while code that only read the threshold is not disturbed when a bundle's usage changes. A view built on the older ObservableObject protocol would redraw in both cases.

Check it worked

The output ends with a line like Test run with 7 tests in 1 suite passed. Change 30 to 60 in usageRules, run swift test again, and see that test fail with a moreThanRemaining(50) error; then change it back.

Step 5 · See strict concurrency catch a background call

Swift 6 checks isolation at compile time. To see it, add a function that is not on the main actor and calls the model directly:

Bash
cd ~/databudget-demo
cat > Sources/DataBudgetKit/BackgroundLogger.swift <<'SWIFT'
func logFromBackground(_ tracker: BundleTracker) {
    try? tracker.recordUsage(10, on: "a")
}
SWIFT

Build it. This build is expected to fail:

Bash
cd ~/databudget-demo
swift build

The compiler reports an error along the lines of call to main actor-isolated instance method 'recordUsage(_:on:)' in a synchronous nonisolated context. Without the check, this call could run on a background thread while SwiftUI reads bundles on the main thread, which is a data race. The fixes are to mark the function @MainActor, or to make it async and write try? await tracker.recordUsage(10, on: "a") so it hops to the main actor (recordUsage still throws, so the try? stays). Remove the file:

Bash
cd ~/databudget-demo
rm Sources/DataBudgetKit/BackgroundLogger.swift
swift build

New app projects in recent Xcode versions can set the module's default isolation to the main actor, so unmarked code runs there unless you opt out. The explicit @MainActor on BundleTracker keeps the package correct whichever default an app uses.

Check it worked

The first build fails with the main actor error, and after rm the build ends with Build complete! again.

Step 6 · Own the model with @State and share it through the environment

The rest of the tutorial is on a Mac in Xcode 27.1. Open your SwiftUI app project (or create one as in the first SwiftUI tutorial) and add the ~/databudget-demo folder as a local package. In current Xcode versions this is File, Add Package Dependencies, then Add Local; names can differ. Add the DataBudgetKit library to your app target.

Decide who owns the tracker. It must be created once for the life of the app, so the App struct owns it with @State. @State keeps the instance across redraws; a plain let tracker = BundleTracker(...) in a view would build a new model, and lose your numbers, every time SwiftUI recreates that view. The tracker then goes into the environment, so any screen can read it without passing it through every init:

Swift
import SwiftUI
import DataBudgetKit

@main
struct DataBudgetApp: App {
    @State private var tracker = BundleTracker(source: SampleBundleSource())

    var body: some Scene {
        WindowGroup {
            BundleListScreen()
                .environment(tracker)
        }
    }
}

The list screen reads the tracker with @Environment and starts the load with .task. SwiftUI runs the task when the screen appears and cancels it if the screen goes away, which is what the cancellation branch in load() handles:

Swift
import SwiftUI
import DataBudgetKit

struct BundleListScreen: View {
    @Environment(BundleTracker.self) private var tracker

    var body: some View {
        NavigationStack {
            content
                .navigationTitle("Data left")
                .toolbar {
                    ToolbarItem {
                        NavigationLink("Settings") { SettingsScreen() }
                    }
                }
        }
        .task { await tracker.load() }
    }

    @ViewBuilder
    private var content: some View {
        switch tracker.loadState {
        case .idle, .loading:
            ProgressView("Loading bundles")
        case .failed(let reason):
            ContentUnavailableView {
                Label("Could not load bundles", systemImage: "wifi.exclamationmark")
            } description: {
                Text(reason)
            } actions: {
                Button("Try again") {
                    Task { await tracker.load() }
                }
            }
        case .loaded:
            List {
                Section {
                    Text("\(tracker.totalRemainingMB) MB left in total")
                        .font(.title2)
                    if tracker.isRunningLow {
                        Label("Running low on data", systemImage: "exclamationmark.triangle")
                    }
                }
                Section("Bundles") {
                    ForEach(tracker.bundles) { bundle in
                        BundleRow(bundle: bundle)
                    }
                }
            }
        }
    }
}

#Preview {
    BundleListScreen()
        .environment(BundleTracker(source: SampleBundleSource()))
}

@Environment(BundleTracker.self) finds the tracker by its type. If a screen reads it and no ancestor called .environment(tracker), the app stops with an error naming the missing type, which is why the preview passes its own tracker.

Check it worked

The preview shows "Loading bundles" for under half a second, then "980 MB left in total" and two bundle rows. In the Simulator the same screen appears after launch. If the preview crashes, check that it calls .environment(...).

Step 7 · Edit view-local state through a @Binding

Each row has a stepper for "how much did I use?". That number belongs to the row and nobody else, so the row owns it with @State. The stepper itself is a separate child view that changes the number but does not own it, so it takes a @Binding, and the row passes $draftMB:

Swift
import SwiftUI
import DataBudgetKit

struct BundleRow: View {
    @Environment(BundleTracker.self) private var tracker
    let bundle: DataBundle
    @State private var draftMB = 50
    @State private var errorText: String?

    var body: some View {
        VStack(alignment: .leading, spacing: 8) {
            Text(bundle.name).font(.headline)
            Text("\(bundle.remainingMB) of \(bundle.sizeMB) MB left")
                .foregroundStyle(.secondary)
            UsageStepper(amountMB: $draftMB)
            Button("Log \(draftMB) MB used", action: logUsage)
                .buttonStyle(.borderless)
            if let errorText {
                Text(errorText).foregroundStyle(.red)
            }
        }
    }

    private func logUsage() {
        do {
            try tracker.recordUsage(draftMB, on: bundle.id)
            errorText = nil
        } catch {
            errorText = error.message
        }
    }
}

struct UsageStepper: View {
    @Binding var amountMB: Int

    var body: some View {
        Stepper("\(amountMB) MB", value: $amountMB, in: 10...1000, step: 10)
    }
}

The row gets bundle as a plain let. It never changes the bundle itself; it asks the tracker, which applies the rules and updates bundles, and SwiftUI then redraws the row with the new value. Because recordUsage uses a typed throw, error in the catch is already a UsageError, so error.message needs no cast.

The rule for @State is that it is private to the view that declares it. If you find yourself wanting to set a child's @State from its parent, the parent should own the value and pass a binding instead.

Check it worked

In the preview or Simulator, step the "Night 1 GB" row up to 100 MB and tap "Log 100 MB used": the row changes to "700 of 1000 MB left" and the total to 880 MB. On the "Weekly 1.5 GB" row, step to 200 MB and log it: the row shows "Only 180 MB left on this bundle." in red and the numbers do not change.

Step 8 · Bind a setting to the shared model with @Bindable

The settings screen changes lowDataThresholdMB on the shared tracker. @Environment gives you the object, but not the $ bindings a Stepper needs. @Bindable adds them. Declare it as a local variable inside body, from the environment value:

Swift
import SwiftUI
import DataBudgetKit

struct SettingsScreen: View {
    @Environment(BundleTracker.self) private var tracker

    var body: some View {
        @Bindable var tracker = tracker
        Form {
            Section("Warning") {
                Stepper(
                    "Warn below \(tracker.lowDataThresholdMB) MB",
                    value: $tracker.lowDataThresholdMB,
                    in: 50...2000,
                    step: 50
                )
            }
        }
        .navigationTitle("Settings")
    }
}

$tracker.lowDataThresholdMB writes straight to the shared model, so the list screen sees the new limit at once. Only a public, settable var can be bound like this: $tracker.bundles does not compile, because bundles is private(set). That is the point of the earlier design: settings the person controls are bindable, and data with rules goes through methods.

A short summary of who owns what in this app:

  • @State in DataBudgetApp: owns the one BundleTracker.
  • @Environment in each screen: reads that tracker.
  • @Bindable in SettingsScreen: makes bindings to the tracker's settable properties.
  • @State in BundleRow: owns the draft amount and the error text.
  • @Binding in UsageStepper: edits the row's draft without owning it.

Check it worked

Tap Settings, raise the limit to 1000 MB and go back: the list now shows "Running low on data". Lower it to 500 MB and the warning goes away. If you log usage so the total falls under the limit, the warning appears without you visiting Settings.

Step 9 · Clean up

The package is only in ~/databudget-demo. If you added it to an Xcode project, remove the package reference there first (select it in the project navigator and delete the reference), then delete the folder:

Bash
rm -rf ~/databudget-demo

Check it worked

ls ~/databudget-demo reports that there is no such file or directory.

Next steps

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.