In SwiftUI, what do onChange(of:initial:_:)'s initial parameter and two-value closure give you, and when is onReceive the better fit?
answer
- iOS 17 replaced the one-value form
- old and new in one closure
- initial runs on first appearance
- a value versus a publisher's events
basics
~20 sonChange(of:initial:_:), added in iOS 17, runs a synchronous action when an Equatable value changes, can pass both old and new values, and with initial: true also runs on first appearance; onReceive reacts to each event a Combine publisher emits.
solid answer
~40 sIn iOS 17 SwiftUI deprecated `onChange(of:perform:)`, which passed only the new value, and added `onChange(of:initial:_:)` with either an `oldValue, newValue` closure or a zero-parameter one. `initial: true` also runs the action when the view first appears, replacing the duplicate `onAppear` call people wrote to sync the starting value. The value must be `Equatable`, and the action runs when it differs between updates. Apple's documentation says the action may run on the main actor, so keep it short and synchronous; to start async work from a value change, `task(id:)` is better because it cancels the previous run. `onReceive(_:perform:)` fits a Combine publisher of events rather than a value in view state, and its `Failure` type must be `Never`.
code
swift · 25 linesimport SwiftUI
struct SymbolPicker: View {
let symbols: [String]
let onSelect: (String) -> Void
@State private var selected = "XYZ"
@State private var lastSwitch = ""
var body: some View {
VStack {
Picker("Symbol", selection: $selected) {
ForEach(symbols, id: \.self) { Text($0) }
}
Text(lastSwitch)
}
// Runs on first appearance and on every later change.
.onChange(of: selected, initial: true) {
onSelect(selected)
}
// Runs on changes only, with both values.
.onChange(of: selected) { oldValue, newValue in
lastSwitch = "Switched from \(oldValue) to \(newValue)"
}
}
}go deeper
Recall that onChange runs an action when a watched value changes, and that onReceive listens to a publisher.
Explain the iOS 17 forms, what initial: true adds, and why the value must be Equatable.
Show when a value change should drive task(id:) instead of onChange, and how to migrate deprecated one-value closures safely.
Set the team convention: onChange for short synchronous reactions, task(id:) for async work, onReceive only at publisher boundaries.
## The forms SwiftUI ships `onChange` attaches a **synchronous** action that runs when a value you name changes. iOS 17 reshaped it: | Form | Closure | Status | |---|---|---| | `onChange(of:perform:)` | `(newValue) -> Void` | deprecated in iOS 17 | | `onChange(of:initial:_:)` | `(oldValue, newValue) -> Void` | iOS 17 and later | | `onChange(of:initial:_:)` | `() -> Void` | iOS 17 and later | The deprecation message points at the replacement: use `onChange` "with a two or zero parameter action closure instead". The same two forms exist on `Scene`, so an app's scenes can react to values too. Key facts about the current forms: - The observed value must conform to `Equatable`; SwiftUI compares it across updates and runs the action when it differs. - `initial` defaults to `false`. Set to `true`, the action **also runs when the view first appears**. - The two-value closure receives the previous and the new value, so comparisons need no extra state. - Apple's documentation notes that the new version of the closure is called on a change, so values it captures are the ones current when the observed value takes its new value. ## What initial: true is for Before iOS 17 a common pattern synced something once at start in `onAppear` and then again on every change in `onChange`, two closures doing the same job. `initial: true` merges them: one action handles the first value and every later one. Typical uses: - Telling a model or a delegate which item is selected, starting with the default. - Applying a setting stored elsewhere as soon as the screen shows. - Logging the starting value and every switch with one code path. On the first run there is no earlier value to compare with, so code that branches on old versus new should be written for that case or use the zero-parameter form, as the code example does. ## Keep the action short Apple's documentation warns that the system may call the action on the main actor, so long-running work in it should be avoided. Because the closure is synchronous, people often start a `Task { }` inside it to load data for the new value. That task is unstructured: the next change starts another one without cancelling the first, and the two race to write state. For async work driven by a value, `task(id:)` is the better tool, because SwiftUI cancels the previous run whenever the value changes. ## onReceive for publishers `onReceive(_:perform:)` solves a different problem: reacting to each value a **Combine publisher** emits, such as a `PassthroughSubject` your model exposes or the projected publisher of a `@Published` property. Its requirements and behaviour: 1. The publisher's `Failure` type must be `Never`, so errors are handled upstream, for example with `replaceError(with:)`. 2. The action receives each output; there is no old value and no `initial`. 3. It fits event streams that do not live in view state. When the thing you watch is already a value the view reads, `onChange` is simpler. How to build and transform the publisher is a Combine subject; `onReceive` is just SwiftUI's subscription point. ## Migrating from the deprecated form Code written for iOS 14 to 16 often contains `onChange(of: value) { newValue in ... }`. With a deployment target of iOS 17 or later the compiler reports it as deprecated. The migration is mechanical but worth reading line by line: - If the closure only used `newValue`, switch to the zero-parameter form and read the property directly; the documentation says the new closure sees current captured values. - If the closure compared against a previous value saved in extra `@State`, switch to the two-value form and delete that state. - If an `onAppear` next to it repeated the same call, replace both with one `onChange` that passes `initial: true`. Each step removes code, which is the point of the iOS 17 change. ## Choosing between them - A value in state, a binding or the environment changed: `onChange(of:initial:_:)`. - The same, plus you need the starting value: add `initial: true`. - The change should start or restart async work: `task(id:)`. - A publisher emits events: `onReceive(_:perform:)`. Kept to these roles, each modifier stays small, and the deprecated one-parameter form can be removed during an iOS 17 baseline migration.
- Why not start a Task inside onChange to load data for the new value?That `Task` is unstructured, so the next change starts another without cancelling the first, and a slow earlier load can overwrite a newer one. It also outlives the view. Using `task(id:)` with the value as the id makes SwiftUI cancel the previous run on each change and when the view disappears.
- How do you subscribe with onReceive to a publisher that can fail?`onReceive` requires `Failure == Never`, so handle errors before it: map them to a fallback with `replaceError(with:)` or a similar Combine operator, then pass the result. The view then only sees outputs, and error policy stays with the model that owns the publisher.
- onChange(of:perform:) with one newValue closure is still the current API.
- onChange runs on first appearance by default, without passing initial: true.
- onChange can watch any value, whether or not it is Equatable.
- A Task started in onChange is cancelled when the value changes again.
- onReceive accepts any publisher, including one that can fail with an error.
Assumes the iOS 27 SDK: the two-value and zero-parameter onChange forms with initial arrived in iOS 17, which deprecated onChange(of:perform:).