SwiftUI state rules for the Observation framework (@Observable with @State, @Environment and @Bindable) plus ObservableObject guidance for older OS targets.
.cursor/rules/swiftui-state-management.mdc. Downloaded files need to be placed in that repository path.---
description: "SwiftUI state rules for the Observation framework (@Observable with @State, @Environment and @Bindable) plus ObservableObject guidance for older OS targets."
globs: "**/*"
alwaysApply: false
---
Apply these rules when managing state in SwiftUI views.
## Principles
- Each piece of data has one source of truth. Views read it or receive a binding; they do not keep their own copies.
- Keep business logic in model types that can be tested without a view; views describe UI from state.
- Prefer value types (`struct`, `enum`) for data; use a reference-type model when several views must observe the same changing object.
## Choosing a property wrapper (iOS 17 / macOS 14 and later)
- `@State` for simple values a view owns (`isEditing`, a draft string), and to own an `@Observable` model instance created by that view.
- `let` for values a child only reads; `@Binding` when the child must change a parent's value type.
- `@Observable` classes for shared models. SwiftUI tracks only the properties a view's body reads.
- `@Environment(Model.self)` to read a model injected with `.environment(model)` higher in the hierarchy.
- `@Bindable` to create bindings (`$model.name`) to properties of an `@Observable` object the view does not own.
```swift
import SwiftUI
import Observation
@MainActor
@Observable
final class ProfileModel {
enum LoadState: Equatable { case idle, loading, loaded, failed(String) }
var name = ""
var loadState: LoadState = .idle
func load(using fetch: () async throws -> String) async {
loadState = .loading
do {
name = try await fetch()
loadState = .loaded
} catch {
loadState = .failed(error.localizedDescription)
}
}
}
struct ProfileScreen: View {
@State private var model = ProfileModel()
var body: some View {
ProfileEditor()
.environment(model)
}
}
struct ProfileEditor: View {
@Environment(ProfileModel.self) private var model
var body: some View {
@Bindable var model = model
Form {
TextField("Name", text: $model.name)
if case .failed(let message) = model.loadState {
Text(message).foregroundStyle(.red)
}
}
}
}
```
## Older deployment targets
- If the app supports iOS 16 / macOS 13 or earlier, use `ObservableObject` with `@Published` properties, `@StateObject` in the owning view, `@ObservedObject` in children and `@EnvironmentObject` for injected objects. Do not mix both systems for the same model.
## Naming
- Name Boolean state as a question (`isEditing`, `hasError`, `shouldShowAlert`); name other state by what it holds.
- Name action methods by intent (`save()`, `toggleFavorite()`); suffix models consistently (`ProfileModel` or `ProfileViewModel`, as the project does).
- Represent states with a fixed set of cases as an `enum` (with associated values for data or errors) instead of several Booleans.
## Pitfalls
- Creating an observable model in a child view with a plain `let`/`var` initializer: it is recreated on every parent update. Own it with `@State` (or `@StateObject` on older targets).
- Using `@State` for data that a parent already owns: pass it as a value or `@Binding` instead.
- Updating UI state from a background task: mark models `@MainActor` and keep async work in `Task`/`.task {}`.
- Swallowing errors: surface them through state so the view can show them.
Cursor rules for Next.js 14+ App Router projects updated for Next.js 16 with async params, validated Route Handlers, generateMetadata and proxy.ts in place of middleware.
Cursor rules for strict TypeScript: compiler checks beyond strict, interfaces vs type aliases, real type guards, discriminated unions, utility types and branded IDs.
Cursor rules for Tailwind CSS v4: automatic class sorting, mobile-first breakpoints, CVA variants with merging, class-based dark mode via @custom-variant, and CSS-first @theme configuration.
Cursor
coding
Illustrative input and expected result. This example is a verification guide, not a recorded model run.
Content reviewed .
An iOS 17+ app uses ObservableObject view models with @Published, creates them with @ObservedObject in child views (so they reset), and tracks loading with isLoading/hasError Booleans.
Using the SwiftUI State Management rule, migrate ProfileView and ProfileViewModel (deployment target iOS 17).
ProfileModel becomes an @MainActor @Observable class with an enum load state; the owning view holds it in @State and injects it with .environment; child editors read it with @Environment and use @Bindable for TextField bindings; no @Published/@StateObject remain for this model.
Cursor applies project rules stored as .mdc files in .cursor/rules. Each rule's frontmatter (description, globs, alwaysApply) decides whether it is always included, attached to matching files, chosen by the agent from its description, or only used when you @-mention it. Cursor also reads AGENTS.md in the project root and subdirectories for plain-Markdown instructions.
.cursor/rules/swiftui-state-management.mdcStarting point, not a tested configuration for your repository. Attached when files matching the globs are in context (alwaysApply: false with globs). Review the instructions, adapt the file paths and run your project's existing checks.
---
description: "SwiftUI State Management project conventions"
globs: "**/*"
alwaysApply: false
---
Apply these rules when managing state in SwiftUI views.
## Principles
- Each piece of data has one source of truth. Views read it or receive a binding; they do not keep their own copies.
- Keep business logic in model types that can be tested without a view; views describe UI from state.
- Prefer value types (`struct`, `enum`) for data; use a reference-type model when several views must observe the same changing object.
## Choosing a property wrapper (iOS 17 / macOS 14 and later)
- `@State` for simple values a view owns (`isEditing`, a draft string), and to own an `@Observable` model instance created by that view.
- `let` for values a child only reads; `@Binding` when the child must change a parent's value type.
- `@Observable` classes for shared models. SwiftUI tracks only the properties a view's body reads.
- `@Environment(Model.self)` to read a model injected with `.environment(model)` higher in the hierarchy.
- `@Bindable` to create bindings (`$model.name`) to properties of an `@Observable` object the view does not own.
```swift
import SwiftUI
import Observation
@MainActor
@Observable
final class ProfileModel {
enum LoadState: Equatable { case idle, loading, loaded, failed(String) }
var name = ""
var loadState: LoadState = .idle
func load(using fetch: () async throws -> String) async {
loadState = .loading
do {
name = try await fetch()
loadState = .loaded
} catch {
loadState = .failed(error.localizedDescription)
}
}
}
struct ProfileScreen: View {
@State private var model = ProfileModel()
var body: some View {
ProfileEditor()
.environment(model)
}
}
struct ProfileEditor: View {
@Environment(ProfileModel.self) private var model
var body: some View {
@Bindable var model = model
Form {
TextField("Name", text: $model.name)
if case .failed(let message) = model.loadState {
Text(message).foregroundStyle(.red)
}
}
}
}
```
## Older deployment targets
- If the app supports iOS 16 / macOS 13 or earlier, use `ObservableObject` with `@Published` properties, `@StateObject` in the owning view, `@ObservedObject` in children and `@EnvironmentObject` for injected objects. Do not mix both systems for the same model.
## Naming
- Name Boolean state as a question (`isEditing`, `hasError`, `shouldShowAlert`); name other state by what it holds.
- Name action methods by intent (`save()`, `toggleFavorite()`); suffix models consistently (`ProfileModel` or `ProfileViewModel`, as the project does).
- Represent states with a fixed set of cases as an `enum` (with associated values for data or errors) instead of several Booleans.
## Pitfalls
- Creating an observable model in a child view with a plain `let`/`var` initializer: it is recreated on every parent update. Own it with `@State` (or `@StateObject` on older targets).
- Using `@State` for data that a parent already owns: pass it as a value or `@Binding` instead.
- Updating UI state from a background task: mark models `@MainActor` and keep async work in `Task`/`.task {}`.
- Swallowing errors: surface them through state so the view can show them.
Ask for a small change to one matching file. Check the tool's loaded context or instruction view, inspect the diff for the requested convention, and run the relevant build or test. A well-formatted file does not guarantee the model follows every instruction.
Cursor's docs recommend keeping individual rules under 500 lines and splitting large rules into composable ones. Cursor's documentation states that it supports AGENTS.md in the project root and in subdirectories. Use AGENTS.md for plain-Markdown instructions you also want other tools to read, and .mdc rules when you need Cursor's scoping options (globs, description-based selection, always-apply).
Documentation checked 2026-11-05: Cursor docs: Rules
Cursor rules for Next.js 14+ App Router projects updated for Next.js 16 with async params, validated Route Handlers, generateMetadata and proxy.ts in place of middleware.
Cursor rules for strict TypeScript: compiler checks beyond strict, interfaces vs type aliases, real type guards, discriminated unions, utility types and branded IDs.
Cursor rules for Tailwind CSS v4: automatic class sorting, mobile-first breakpoints, CVA variants with merging, class-based dark mode via @custom-variant, and CSS-first @theme configuration.