SwiftUI @State Is Now a Macro in Xcode 27 - Lazy Initialization and Migration
@State is usually the first piece of SwiftUI data flow you learn. You mark a property with it, SwiftUI stores the value on your behalf, and the view updates when the value changes.
In Xcode 27, the spelling stays the same, but the implementation doesn't. @State is no longer a property wrapper. It's a Swift macro.
For most views, you won't notice. Your code compiles, your bindings work, and your interface looks the same. The difference appears in two places:
- State that holds a reference type, such as an
@Observablemodel, is now created once instead of every time the view is initialized. - A small number of initializer patterns that compiled in Xcode 26 now produce errors, or compile and behave differently.
This article explains what changed, why it changed, and how to resolve each incompatibility.
Overview
Before Xcode 27, State was a structure marked with @propertyWrapper. The compiler stored a State<Value> instance in your view and evaluated the property's initial value expression whenever it created that instance.
When you build with Xcode 27 or later, SwiftUI uses the State() macro instead. The macro expands your declaration into storage that SwiftUI can initialize on demand, which gives the framework two capabilities the property wrapper never had:
- It evaluates the initial value lazily, the first time SwiftUI needs it.
- It lets the compiler treat the property like any other stored property of the view.
The first capability removes a long-standing performance trap. The second is the source of the new compiler diagnostics.
Understand the cost of eager initialization
Consider a view that owns an observable model:
@Observable
final class JournalStore {
var entries: [Entry] = []
init() {
print("JournalStore created")
}
}
struct JournalView: View {
@State private var store = JournalStore()
var body: some View {
List(store.entries) { entry in
Text(entry.title)
}
}
}Now place that view inside a parent that has state of its own:
struct DashboardView: View {
@State private var isShowingTips = false
var body: some View {
VStack {
Toggle("Show Tips", isOn: $isShowingTips)
JournalView()
}
}
}Each time isShowingTips changes, SwiftUI evaluates the body of DashboardView again, which initializes a new JournalView value. That's expected. View values are lightweight descriptions, and SwiftUI creates them often.
The problem was what happened next. With the property wrapper, initializing JournalView also evaluated JournalStore(). SwiftUI kept the original instance in its state storage and discarded the new one immediately, so the interface stayed correct. But the initializer still ran every time.
For a value type such as Bool or Int, that's harmless. For a class, each discarded instance is a heap allocation, plus whatever work its initializer performs: opening a database, registering observers, starting a network request.
Under the property wrapper, showing this view and toggling the switch three times prints:
JournalStore created
JournalStore created
JournalStore created
JournalStore createdOnly the first instance is ever used.
Developers worked around this in several ways: making the state optional and assigning it in task(priority:_:), moving the model higher in the hierarchy, or keeping model initializers trivially cheap. All of them added ceremony to something that should be simple.
Initialize state lazily with the macro
Build the same code with Xcode 27 and toggle the switch three times:
JournalStore createdThe model is created once, when SwiftUI first creates storage for the view, and never again for the lifetime of that view.
Conceptually, the macro moves your initial value expression into a closure and rewrites the property so that reads and writes go through SwiftUI-managed storage:
// Simplified for illustration. The actual expansion uses SwiftUI-internal types.
struct JournalView: View {
private var storage = StateStorage { JournalStore() }
var store: JournalStore {
get { storage.wrappedValue }
nonmutating set { storage.wrappedValue = newValue }
}
}Because the expression is wrapped in a closure, initializing the view no longer evaluates it. SwiftUI calls the closure when it needs the initial value, and skips it when storage for the view already exists.
The macro also generates the peers you already rely on: _store, which is a State<JournalStore>, and $store, which is a Binding<JournalStore>. To see the full expansion for one of your own properties, Control-click @State in Xcode and choose Expand Macro.
Note: Laziness applies to every inline initial value, not only to classes. A declaration such as
@State private var seed = makeSeed()callsmakeSeed()once. The practical benefit is largest for reference types, because that's where repeated initialization was expensive.
Check availability
You don't opt in to the macro, and you don't need to raise your deployment target. Compiling with Xcode 27 is what selects it.
Apple states that the lazy initialization behavior is back-deployed to the releases that introduced Observation: iOS 17, macOS 14, and the aligned releases of the other platforms.
The reverse is also true. If you build the same project with Xcode 26 or earlier, SwiftUI uses the property wrapper, and the eager behavior returns. Keep that in mind if your team or your continuous integration system still builds with an older toolchain.
Know where lazy initialization stops
The macro makes one specific pattern efficient: an initial value written inline, as part of the property declaration.
It doesn't change what happens when you create the value yourself inside an initializer:
@Observable
final class EntryEditor {
var draft: Entry
init(entry: Entry) {
self.draft = entry
}
}
struct EntryEditorView: View {
@State private var editor: EntryEditor
init(entry: Entry) {
self.editor = EntryEditor(entry: entry)
}
var body: some View {
TextField("Title", text: $editor.draft.title)
}
}The expression EntryEditor(entry: entry) is ordinary code in your initializer. It runs every time the initializer runs, and SwiftUI again keeps only the first instance. In a test where the parent updated three times, this pattern created four EntryEditor instances under Xcode 27, exactly as it did before.
There's a second consequence to remember. State keeps its first value for the lifetime of the view's identity, so if the parent later passes a different entry, the view continues to show the editor it created for the original one.
When a model depends on input from the parent, choose one of these approaches:
- Create the model in the parent, or in a shared owner, and pass it down.
- Give the view a new identity with
id(_:)when the input changes, so SwiftUI creates fresh state. - Keep the state optional and create the model in
task(id:priority:_:), keyed to the input.
Resolve source incompatibilities
Because the macro generates real stored properties and accessors, the compiler now sees details that the property wrapper hid. Three patterns produce errors, and one compiles but behaves differently.
| Diagnostic | Cause | Resolution |
|---|---|---|
variable 'self.x' used before being initialized |
An initializer assigns to a state property that also has an inline initial value | Remove the inline initial value |
| No diagnostic; the assigned value is ignored | Same pattern, with the assignment placed last | Remove the inline initial value |
invalid redeclaration of synthesized property '_x' |
Another property wrapper is composed with @State |
Remove the additional wrapper |
Argument label mismatch when calling self.init |
An extension relies on the private memberwise initializer | Declare the initializer explicitly |
Assign state in an initializer
This view provides an inline initial value for progress, then assigns it again in the initializer:
struct GoalView: View {
let title: String
@State private var progress = 0.0
init(title: String, startingAt progress: Double) {
self.progress = progress
self.title = title
}
var body: some View {
ProgressView(title, value: progress)
}
}Xcode 27 reports:
error: variable 'self.title' used before being initializedDepending on your deployment target, the same problem can appear as 'self' used before all stored properties are initialized.
The diagnostic points at title, which makes it tempting to swap the two assignments. Don't. That version compiles, but it doesn't do what you intend, as the next section explains.
The reason for the error is the inline initial value. Because progress is already initialized when the body of the initializer begins, self.progress = progress isn't an initialization. It's a call to the property's setter, and Swift doesn't allow you to call through self until every stored property has a value.
To fix it, remove the inline initial value and let the initializer provide the only one:
struct GoalView: View {
let title: String
@State private var progress: Double
init(title: String, startingAt progress: Double) {
self.progress = progress
self.title = title
}
var body: some View {
ProgressView(title, value: progress)
}
}Now the assignment initializes the property, which Swift permits in any order.
Avoid assigning over an inline initial value
This version compiles without warnings in Xcode 27:
struct GoalView: View {
let title: String
@State private var progress = 0.0
init(title: String, startingAt progress: Double) {
self.title = title
self.progress = progress
}
var body: some View {
ProgressView(title, value: progress)
}
}At runtime, progress is 0.0, regardless of the value you pass in.
Important: When a state property has an inline initial value, that value takes precedence. SwiftUI discards a value assigned to the same property in the initializer. The compiler doesn't diagnose this, so search your project for views that do both.
The rule to follow is simple: give each state property exactly one source for its initial value. Either write it inline, or assign it in the initializer. Never both.
Remove composed property wrappers
Some projects stack a custom property wrapper on top of @State, for example to clamp a value:
struct VolumeControl: View {
@State @Clamped private var volume = 50
// ...
}Xcode 27 reports:
error: invalid redeclaration of synthesized property '_volume'Both the property wrapper and the macro try to synthesize backing storage named _volume, and the names collide. You may also see property wrapper cannot be applied to a computed property, because the macro has already turned volume into a computed property by the time the wrapper is applied.
Remove the additional wrapper and move its behavior to the place where the value changes:
struct VolumeControl: View {
@State private var volume = 50
var body: some View {
Stepper("Volume: \(volume)") {
setVolume(volume + 10)
} onDecrement: {
setVolume(volume - 10)
}
}
private func setVolume(_ newValue: Int) {
volume = min(max(newValue, 0), 100)
}
}If several views share the rule, put it in the value's type or in a model, rather than in a wrapper around state.
Declare private memberwise initializers explicitly
When every stored property of a structure is private and the structure declares no initializer, Swift synthesizes a private memberwise initializer. Code in the same file, including extensions, can call it:
struct RatingView: View {
@State private var rating = 0
private let maximum: Int
// ...
}
extension RatingView {
init(_ rating: Int, outOf maximum: Int) {
self.init(rating: rating, maximum: maximum)
}
}With the macro, the compiler no longer synthesizes that initializer in the form this code expects, and the call fails:
error: incorrect argument labels in call (have 'rating:maximum:', expected '_:outOf:')The exact wording varies with the shape of the call. You might instead see extraneous argument label or no exact matches in call to initializer. In each case, the cause is the same: the memberwise initializer you're delegating to doesn't exist.
Declare it yourself. Because the initializer now supplies the value for rating, remove the inline initial value at the same time:
struct RatingView: View {
@State private var rating: Int
private let maximum: Int
private init(rating: Int, maximum: Int) {
self.rating = rating
self.maximum = maximum
}
var body: some View {
Stepper("\(rating) of \(maximum)", value: $rating, in: 0...maximum)
}
}
extension RatingView {
init(_ rating: Int, outOf maximum: Int) {
self.init(rating: rating, maximum: maximum)
}
}This incompatibility is limited to the private memberwise initializer. A view with a non-private state property, such as @State var count: Int, still receives a memberwise initializer that you can call as CounterView(count: 3).
Keep what already works
The macro changes how state is stored and initialized. It doesn't change how you use it:
- Declare state as
private, and keep it local to the view that owns it. - Read and write the property directly, and pass
$propertywhere a child needs a binding. - Rely on the view's identity for lifetime. SwiftUI preserves state while the identity is stable and resets it when the identity changes.
- Continue to use
_score = State(initialValue: score)in existing initializers. The form still compiles and behaves as before, although a direct assignment to the property is simpler and has the same effect.
Migrate an existing project
When you first open a project in Xcode 27, work through it in this order:
- Build the project and fix each
used before being initializederror by removing the inline initial value. Don't reorder the assignments. - Search for state properties that have an inline initial value and are also assigned in an initializer. These compile, so the build won't find them for you.
- Replace any property wrapper composed with
@State. - Add explicit initializers where an extension delegated to a private memberwise initializer.
- Review workarounds that existed only to avoid repeated model initialization, such as optional state assigned in a task. If the model takes no input from the parent, an inline initial value is now the simplest correct choice.
If you build with more than one version of Xcode, keep those workarounds until every toolchain you use is Xcode 27 or later.
References
Apple Developer Documentation: State
https://developer.apple.com/documentation/swiftui/state
Apple Technical Note TN3211: Resolving SwiftUI source incompatibilities for State and ContentBuilder
WWDC26: What's new in SwiftUI
https://developer.apple.com/videos/play/wwdc2026/269
Swift Evolution SE-0400: Init Accessors
https://github.com/swiftlang/swift-evolution/blob/main/proposals/0400-init-accessors.md
Final thoughts
The move from property wrapper to macro is the kind of change that's easy to miss, because the code you write looks identical:
@State private var store = JournalStore()What that line means is different. It used to mean "create a store each time this view is initialized, and keep the first one." It now means "create a store when this view first needs one."
That's the behavior most developers assumed they were getting all along. Adopting it costs little: build with Xcode 27, give every state property a single source for its initial value, and remove the workarounds you no longer need.
Thank you for reading. If you have any questions feel free to follow me on X and send me a DM. If this article helped you, Buy me a coffee.