TExcelTAD
Home › Swift › State & Binding

SwiftUI State & Binding

In SwiftUI the UI is a function of state: you never change a label directly. Instead you change the data, and SwiftUI recomputes body and updates the screen. The property wrappers @State and @Binding are how a view owns and shares that data.

Note: SwiftUI code can't run in the browser. The examples are followed by interactive HTML mocks of the iPhone screen, plus runnable plain-Swift models of the same ideas.

@State: data a view owns

Views are structs and are recreated constantly, so a normal var in a view would be reset — and Swift won't even let body modify it. @State moves the value into storage that SwiftUI manages and keeps alive between redraws:

swift
import SwiftUI

struct CounterView: View {
    @State private var count = 0

    var body: some View {
        VStack(spacing: 16) {
            Text("\(count)")
                .font(.system(size: 64, weight: .bold))
            HStack {
                Button("−") { count -= 1 }
                Button("+") { count += 1 }
            }
            .font(.largeTitle)
            .buttonStyle(.bordered)
        }
    }
}

Every tap changes count, and SwiftUI redraws the text. Try the mock:

html · try it yourself
<div style="width:320px;height:360px;margin:12px auto;border:10px solid #1c1c1e;border-radius:44px;background:#fff;font-family:-apple-system,system-ui,sans-serif;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:16px">
  <div id="n" style="font-size:64px;font-weight:700">0</div>
  <div style="display:flex;gap:8px">
    <button onclick="add(-1)" style="font-size:30px;width:64px;border:0;border-radius:10px;background:#e5f0ff;color:#007aff">−</button>
    <button onclick="add(1)" style="font-size:30px;width:64px;border:0;border-radius:10px;background:#e5f0ff;color:#007aff">+</button>
  </div>
</div>
<script>
  let count = 0;
  function add(d) { count += d; document.getElementById('n').textContent = count; }
</script>

Tip: Mark @State properties private. They belong to this view only; other views get access through a binding.

The "state → body" cycle in plain Swift

Here is a runnable model of what SwiftUI does: whenever the state changes, body is evaluated again from scratch:

swift · try it yourself
struct Counter {
    var count = 0

    var body: String {
        "[ - ]  \(count)  [ + ]" + (count >= 3 ? "  🎉" : "")
    }
}

var screen = Counter()
print(screen.body)

for tap in ["+", "+", "+", "-"] {
    screen.count += (tap == "+" ? 1 : -1)
    print("tap \(tap) → redraw:", screen.body)
}
[ - ]  0  [ + ]
tap + → redraw: [ - ]  1  [ + ]
tap + → redraw: [ - ]  2  [ + ]
tap + → redraw: [ - ]  3  [ + ]  🎉
tap - → redraw: [ - ]  2  [ + ]

@Binding: sharing state with a child

A child view often needs to change its parent's state — for example a reusable toggle row. The parent keeps the @State; the child declares a @Binding, and the parent passes $value (the projected value of @State, which is a binding):

swift
struct SettingsView: View {
    @State private var notifications = true

    var body: some View {
        Form {
            SettingRow(title: "Notifications", isOn: $notifications)
            Text(notifications ? "You will get alerts" : "Alerts are muted")
                .foregroundStyle(.secondary)
        }
    }
}

struct SettingRow: View {
    let title: String
    @Binding var isOn: Bool

    var body: some View {
        Toggle(title, isOn: $isOn)
    }
}

Flip the switch: the child changes the binding, and the parent's text updates too, because there is only one source of truth.

html · try it yourself
<div style="width:320px;height:300px;margin:12px auto;border:10px solid #1c1c1e;border-radius:44px;background:#f2f2f7;font-family:-apple-system,system-ui,sans-serif;padding-top:60px;box-sizing:border-box">
  <div style="margin:0 16px;background:#fff;border-radius:10px">
    <label style="display:flex;align-items:center;justify-content:space-between;padding:12px 16px;font-size:17px">Notifications
      <input id="t" type="checkbox" checked onchange="sync()" style="width:44px;height:24px;accent-color:#34c759">
    </label>
    <div id="msg" style="padding:12px 16px;border-top:1px solid #e5e5ea;color:#8e8e93;font-size:17px">You will get alerts</div>
  </div>
</div>
<script>
  function sync() {
    document.getElementById('msg').textContent = document.getElementById('t').checked ? 'You will get alerts' : 'Alerts are muted';
  }
</script>

Bindings modelled in Swift

A binding is essentially a pair of closures — one to read and one to write somebody else's value. This runnable example builds a minimal version:

swift · try it yourself
struct MiniBinding<Value> {
    let get: () -> Value
    let set: (Value) -> Void

    var value: Value {
        get { get() }
        nonmutating set { set(newValue) }
    }
}

final class Store {
    var notifications = true
}

let store = Store()
let binding = MiniBinding(get: { store.notifications },
                          set: { store.notifications = $0 })

print("Child reads:", binding.value)
binding.value = false                // the child writes…
print("Parent sees:", store.notifications)   // …the parent's data changed
Child reads: true
Parent sees: false

Which wrapper when?

Wrapper Owns the data? Typical use
@State yes simple values local to one view (counters, toggles, text input)
@Binding no a child that reads and writes a parent's state
let property no a child that only reads a value
@Observable class + @State yes a model object with several properties shared by many views
@Environment no values provided by the system or an ancestor

Note: For larger apps, put data in a class marked with the @Observable macro (iOS 17+). Views that read its properties update automatically when they change.

Test yourself

Why can't a SwiftUI view simply use a plain var count = 0 for changing data?

  1. Structs can't have var properties
  2. Views are recreated often and body can't mutate the struct; @State keeps the value in SwiftUI-managed storage
  3. Int is not allowed in views
  4. Plain vars are always private

Given @State private var isOn = false, what do you pass to a child's @Binding var isOn: Bool?

  1. isOn
  2. $isOn
  3. &isOn
  4. @isOn

A child view only needs to display a value, never change it. What should it use?

  1. @State
  2. @Binding
  3. A plain let property
  4. @Environment