This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
mobilecritical PriorityID: swiftui-ios18-observation-swiftdata-guardrails

SwiftUI iOS 18 Observation Framework & SwiftData Actor Confinement

Enforces strict adherence to iOS 18 Observation framework migration patterns and SwiftData concurrency guarantees. Prohibits mixing Combine-based ObservableObject/Published patterns with the @Observable macro, prevents cross-actor ModelContext and PersistentModel access, and mandates chunked batch saves within dedicated ModelActor instances.

Prohibited Anti-Pattern: Mixing ObservableObject with @Observable, Passing ModelContext Across Actor Boundaries, and Performing Unbatched Bulk SwiftData Writes

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: SwiftUI iOS 18 Observation Framework & SwiftData Actor Confinement - Enforces strict adherence to iOS 18 Observation framework migration patterns and SwiftData concurrency guarantees. Prohibits mixing Combine-based ObservableObject/Published patterns with the @Observable macro, prevents cross-actor ModelContext and PersistentModel access, and mandates chunked batch saves within dedicated ModelActor instances.
globs: **/*.swift
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/swiftui-ios18-observation-swiftdata-guardrails"
---

# SwiftUI iOS 18 Observation Framework & SwiftData Actor Confinement

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Mixing ObservableObject with @Observable, Passing ModelContext Across Actor Boundaries, and Performing Unbatched Bulk SwiftData Writes

## System Constraints
You are a Principal Mobile Architect enforcing strict iOS 18 SwiftUI Observation and SwiftData architectural invariants. You strictly mandate migration from ObservableObject to @Observable, eliminate Combine wrapper leakage (@StateObject, @ObservedObject, @Published), enforce Swift 6 concurrency safety regarding ModelContext and PersistentModel actor-isolation, and mandate explicit ModelActor usage for transactional and chunked batch operations.

## Strict Guidelines
- Engineers MUST ALWAYS annotate observable domain and view models with the '@Observable' macro and use regular '@State', property declarations, or '@Bindable' in SwiftUI views, completely removing '@StateObject', '@ObservedObject', and '@Published'.
- Engineers MUST NOT pass 'ModelContext' or live 'PersistentModel' instances across actor or concurrency boundaries; models must be passed via 'PersistentIdentifier' across isolation contexts.
- Engineers MUST ALWAYS isolate heavy SwiftData batch insertions, deletions, and background mutations inside a custom 'ModelActor' initialized with the shared 'ModelContainer'.
- Services MUST execute batch persistence in explicit chunk sizes (e.g., chunks of 500-1000 items) and perform explicit 'try context.save()' calls followed by clearing ephemeral references to manage peak resident memory.
- Components NEVER use the '@Query' macro inside view models or background workers; '@Query' is strictly reserved for SwiftUI View declarations bound to MainActor.
- Engineers MUST explicitly bind editable fields of '@Observable' models inside views using the '@Bindable' property wrapper, avoiding manual Binding projection antipatterns.

## Bad vs Good Implementations
### Migrating Observable State & Bindings from ObservableObject to @Observable

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Using ObservableObject and @StateObject prevents iOS 18 fine-grained observation tracking, causes redundant view graph invalidations, and couples the architecture to deprecated Combine wrappers.
```swift
import SwiftUI
import Combine

// Anti-pattern: Legacy Combine-based ObservableObject in iOS 18
final class UserProfileViewModel: ObservableObject {
    @Published var username: String = ""
    @Published var notificationsEnabled: Bool = false
}

struct UserProfileView: View {
    @StateObject private var viewModel = UserProfileViewModel()
    
    var body: some View {
        Form {
            TextField("Username", text: $viewModel.username)
            Toggle("Notifications", isOn: $viewModel.notificationsEnabled)
        }
    }
}
```

#### Production Standard (Correct)
> **Standard**: Leverages the @Observable macro for fine-grained dependency tracking, stores view lifecycle state via @State, and uses @Bindable to safely project two-way bindings.
```swift
import SwiftUI
import Observation

// Production standard: Pure Observation framework pattern
@Observable
@MainActor
final class UserProfileViewModel {
    var username: String = ""
    var notificationsEnabled: Bool = false
}

struct UserProfileView: View {
    @State private var viewModel = UserProfileViewModel()
    
    var body: some View {
        @Bindable var bindableViewModel = viewModel
        Form {
            TextField("Username", text: $bindableViewModel.username)
            Toggle("Notifications", isOn: $bindableViewModel.notificationsEnabled)
        }
    }
}
```

### SwiftData Thread Confinement & Chunked Batch Operations via ModelActor

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: ModelContext is actor-bound (typically MainActor when injected via SwiftUI). Mutating it or calling save() inside a detached task causes data races, undefined behavior, and fatal crashes under Swift 6 mode.
```swift
import SwiftData
import SwiftUI

struct SyncService {
    // Anti-pattern: Leaking ModelContext across concurrent tasks and unbound saving
    func importRecords(payloads: [PayloadDTO], context: ModelContext) async throws {
        Task.detached {
            for payload in payloads {
                let item = ItemRecord(id: payload.id, timestamp: payload.timestamp)
                context.insert(item)
            }
            try context.save() // Crash: Concurrent access to actor-isolated ModelContext
        }
    }
}
```

#### Production Standard (Correct)
> **Standard**: Uses the @ModelActor macro to guarantee concurrency isolation with its own private ModelContext and ModelExecutor, processing mutations in manageable chunks to prevent memory bloat and concurrency violations.
```swift
import Foundation
import SwiftData

// Production standard: Custom ModelActor for isolated batch processing
@ModelActor
public actor DataImporterActor {
    public func importRecords(payloads: [PayloadDTO], chunkSize: Int = 500) throws {
        for (index, payload) in payloads.enumerated() {
            let item = ItemRecord(id: payload.id, timestamp: payload.timestamp)
            modelContext.insert(item)
            
            if (index + 1) % chunkSize == 0 {
                try modelContext.save()
            }
        }
        
        if modelContext.hasChanges {
            try modelContext.save()
        }
    }
}
```

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 18 Observation Framework & SwiftData Actor Confinement

SwiftUI iOS 18 Observation Framework & SwiftData Actor Confinement defines an industrial-grade behavioral standard for mobile engineering. Enforces strict adherence to iOS 18 Observation framework migration patterns and SwiftData concurrency guarantees. Prohibits mixing Combine-based ObservableObject/Published patterns with the @Observable macro, prevents cross-actor ModelContext and PersistentModel access, and mandates chunked batch saves within dedicated ModelActor instances. 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: Mixing ObservableObject with @Observable, Passing ModelContext Across Actor Boundaries, and Performing Unbatched Bulk SwiftData Writes 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 DriftMixing ObservableObject with @Observable, Passing ModelContext Across Actor Boundaries, and Performing Unbatched Bulk SwiftData WritesCritical
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

Engineers MUST ALWAYS annotate observable domain and view models with the '@Observable' macro and use regular '@State', property declarations, or '@Bindable' in SwiftUI views, completely removing '@StateObject', '@ObservedObject', and '@Published'.

Engineers MUST ALWAYS annotate observable domain and view models with the '@Observable' macro and use regular '@State', property declarations, or '@Bindable' in SwiftUI views, completely removing '@StateObject', '@ObservedObject', and '@Published'.

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

Engineers MUST NOT pass 'ModelContext' or live 'PersistentModel' instances across actor or concurrency boundaries

Engineers MUST NOT pass 'ModelContext' or live 'PersistentModel' instances across actor or concurrency boundaries; models must be passed via 'PersistentIdentifier' across isolation contexts.

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

Engineers MUST ALWAYS isolate heavy SwiftData batch insertions, deletions, and background mutations inside a custom 'ModelActor' initialized with the shared 'ModelContainer'.

Engineers MUST ALWAYS isolate heavy SwiftData batch insertions, deletions, and background mutations inside a custom 'ModelActor' initialized with the shared 'ModelContainer'.

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

Services MUST execute batch persistence in explicit chunk sizes (e.g., chunks of 500-1000 items) and perform explicit 'try context.save()' calls followed by clearing ephemeral references to manage peak resident memory.

Services MUST execute batch persistence in explicit chunk sizes (e.g., chunks of 500-1000 items) and perform explicit 'try context.save()' calls followed by clearing ephemeral references to manage peak resident memory.

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

Components NEVER use the '@Query' macro inside view models or background workers

Components NEVER use the '@Query' macro inside view models or background workers; '@Query' is strictly reserved for SwiftUI View declarations bound to MainActor.

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.
6

Engineers MUST explicitly bind editable fields of '@Observable' models inside views using the '@Bindable' property wrapper, avoiding manual Binding projection antipatterns.

Engineers MUST explicitly bind editable fields of '@Observable' models inside views using the '@Bindable' property wrapper, avoiding manual Binding projection antipatterns.

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 18 Observation Framework & SwiftData Actor Confinement critical for AI coding assistants?

Enforces strict adherence to iOS 18 Observation framework migration patterns and SwiftData concurrency guarantees. Prohibits mixing Combine-based ObservableObject/Published patterns with the @Observable macro, prevents cross-actor ModelContext and PersistentModel access, and mandates chunked batch saves within dedicated ModelActor instances. 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 (Mixing ObservableObject with @Observable, Passing ModelContext Across Actor Boundaries, and Performing Unbatched Bulk SwiftData Writes) 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