This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
mobilehigh PriorityID: swiftui-observation-framework-ios17

SwiftUI iOS 17+ @Observable Macro Migration & State Isolation Standard

Production state architecture standard for modern SwiftUI (iOS 17+ / Swift 6). Mandates migrating from legacy ObservableObject and @Published to the native @Observable macro, using @State for model ownership, @Bindable for two-way bindings, and eliminating redundant view body invalidations.

Prohibited Anti-Pattern: AI writes legacy class ViewModel: ObservableObject with @Published and @StateObject in iOS 17+ codebases, causing whole-view re-renders on every property change.

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: SwiftUI iOS 17+ @Observable Macro Migration & State Isolation Standard - Production state architecture standard for modern SwiftUI (iOS 17+ / Swift 6). Mandates migrating from legacy ObservableObject and @Published to the native @Observable macro, using @State for model ownership, @Bindable for two-way bindings, and eliminating redundant view body invalidations.
globs: **/*.swift
alwaysApply: false
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/swiftui-observation-framework-ios17"
---

# SwiftUI iOS 17+ @Observable Macro Migration & State Isolation Standard

> **Severity**: HIGH | **Category**: mobile
> **Anti-Pattern Warning**: AI writes legacy class ViewModel: ObservableObject with @Published and @StateObject in iOS 17+ codebases, causing whole-view re-renders on every property change.

## System Constraints
You are an iOS and SwiftUI Systems Engineer. In iOS 17+ and Swift 6, DO NOT use ObservableObject, @Published, or @StateObject. These legacy patterns trigger whole-view re-evaluations whenever ANY published property changes. Always use the native @Observable macro from the Observation framework, which tracks property access with granular field-level precision.

## Strict Guidelines
- MUST annotate model classes with @Observable instead of conforming to ObservableObject.
- MUST NOT use @Published inside @Observable classes (all stored properties are observed automatically).
- MUST instantiate observable models in views using @State var model = Model().
- MUST use @Bindable var model = model inside view bodies when two-way bindings ($model.property) are needed.
- SHOULD isolate background data mutation inside Swift 6 ModelActor or @MainActor boundaries.

## Bad vs Good Implementations
### Migrating from ObservableObject to @Observable Macro in SwiftUI

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: ObservableObject invalidates the entire View body whenever ANY @Published property changes. In complex views, this causes massive frame drops and redundant child re-evaluations.
```swift
// FATAL: Legacy ObservableObject causes unnecessary full-view re-renders
import SwiftUI

class UserProfileViewModel: ObservableObject {
  @Published var username: String = ""
  @Published var avatarUrl: String = ""
}

struct ProfileView: View {
  // DEPRECATED in iOS 17+: Every single character typed in username re-evaluates the whole view!
  @StateObject private var viewModel = UserProfileViewModel()
  
  var body: some View {
    TextField("Username", text: $viewModel.username)
  }
}
```

#### Production Standard (Correct)
> **Standard**: The @Observable macro tracks property reads with fine-grained dependency tracking. Views re-render only when the specific properties they access change, improving rendering efficiency.
```swift
import SwiftUI
import Observation

// Modern Swift Observation Macro (Zero @Published boilerplate)
@Observable
final class UserProfileModel {
  var username: String = ""
  var avatarUrl: String = ""
}

struct ProfileView: View {
  // Initialized with standard @State in iOS 17+
  @State private var model = UserProfileModel()

  var body: some View {
    // @Bindable enables two-way bindings to @Observable model properties
    @Bindable var model = model
    
    VStack {
      // Only views reading model.username re-render when username updates!
      TextField("Username", text: $model.username)
    }
  }
}
```

Recommended MCP Servers (mcp-serverlist.com)

Equip agent with system tools to verify code for this stack.

Recommended Agent Skills (askills.dev)

Ready-to-use executable skill functions tailored to this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: SwiftUI iOS 17+ @Observable Macro Migration & State Isolation Standard

SwiftUI iOS 17+ @Observable Macro Migration & State Isolation Standard defines an industrial-grade behavioral standard for mobile engineering. Production state architecture standard for modern SwiftUI (iOS 17+ / Swift 6). Mandates migrating from legacy ObservableObject and @Published to the native @Observable macro, using @State for model ownership, @Bindable for two-way bindings, and eliminating redundant view body invalidations. Modern software architectures require strict adherence to deterministic patterns to guarantee high availability, maintainability, and zero security vulnerabilities.

Framework Paradigm Shift & Drift MechanicsLLMs are trained on millions of open-source repositories containing outdated code, legacy idioms, and unpatched antipatterns. When coding assistants generate implementations for this stack, they default to common statistical tokens: AI writes legacy class ViewModel: ObservableObject with @Published and @StateObject in iOS 17+ codebases, causing whole-view re-renders on every property change. Without an explicit system instruction file, developers spend hours debugging silent failures.
Failure Modes & Production Blast Radius

Hazard Analysis: What Breaks Without This Rule

The following failure modes have been cataloged from hundreds of hours of production code reviews where AI assistants produced non-compliant implementations:

Failure ModeAI Symptom (The Anti-Pattern)SeverityProduction Impact & Remedy
AI Hallucination & Deprecation DriftAI writes legacy class ViewModel: ObservableObject with @Published and @StateObject in iOS 17+ codebases, causing whole-view re-renders on every property change.High
Violating this industrial standard introduces regression bugs, security risks, and unexpected runtime failures in production.
Enforce explicit behavioral system directives across all AI coding assistants in your repository.
Silent Architecture InconsistencyAI assistants produce mixed paradigms across files, creating fragmented codebase conventions.Medium
Increases cognitive load during code reviews and leads to maintenance debt across engineering teams.
Pin project conventions in .cursor/rules, CLAUDE.md, and AGENTS.md so all team agents follow identical guardrails.
Architectural Directives in Detail

Step-by-Step Production Directives

Each rule constraint below is injected into the AI agent's system prompt to establish deterministic boundaries:

1

MUST annotate model classes with @Observable instead of conforming to ObservableObject.

MUST annotate model classes with @Observable instead of conforming to ObservableObject.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
2

MUST NOT use @Published inside @Observable classes (all stored properties are observed automatically).

MUST NOT use @Published inside @Observable classes (all stored properties are observed automatically).

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
3

MUST instantiate observable models in views using @State var model = Model().

MUST instantiate observable models in views using @State var model = Model().

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
4

MUST use @Bindable var model = model inside view bodies when two-way bindings ($model.property) are needed.

MUST use @Bindable var model = model inside view bodies when two-way bindings ($model.property) are needed.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
5

SHOULD isolate background data mutation inside Swift 6 ModelActor or @MainActor boundaries.

SHOULD isolate background data mutation inside Swift 6 ModelActor or @MainActor boundaries.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
Technical Questions & Answers

Frequently Asked Technical Questions

Common questions developers face when configuring AI coding assistants for this stack:

Q:Why is SwiftUI iOS 17+ @Observable Macro Migration & State Isolation Standard critical for AI coding assistants?

Production state architecture standard for modern SwiftUI (iOS 17+ / Swift 6). Mandates migrating from legacy ObservableObject and @Published to the native @Observable macro, using @State for model ownership, @Bindable for two-way bindings, and eliminating redundant view body invalidations. Without explicit behavioral boundaries, AI coding assistants (Cursor, Claude Code, Windsurf, Codex) rely on training data averages, which frequently produce deprecated, inefficient, or vulnerable code patterns.

Q:How does adopting this rule prevent AI hallucinations?

This rule explicitly declares what the AI must avoid (AI writes legacy class ViewModel: ObservableObject with @Published and @StateObject in iOS 17+ codebases, causing whole-view re-renders on every property change.) and prescribes verified positive examples. Grounding the LLM with negative and positive pairs eliminates guesswork.

Q:Which AI coding environments are supported?

This specification is multi-platform compatible: Cursor (.cursor/rules/*.mdc & .cursorrules), Anthropic Claude Code (CLAUDE.md), Windsurf (.windsurfrules), Codex / Cline (AGENTS.md), and GitHub Copilot (.github/copilot-instructions.md).

Q:Can I combine this rule with other technology stacks?

Yes. Use the Interactive Stack Builder or download an Agent Pack to merge this rule with other frontend, backend, database, security, and DevOps rules without syntax collision.

Open Specification · CC BY 4.0·Free for Personal, Team & Commercial In-Repo Use

Citation & Open Source Attribution Guidelines

This specification is licensed under Creative Commons Attribution 4.0 International (CC BY 4.0). You are completely free to adapt and share this rule in your workspace. If citing, including in public AI benchmark datasets, or redistributing, attribution to AgentRules.org is required.

Related MOBILE Rules

View all rules →
1 Rule in Stack

SwiftUI