agentleFS
moasqmoasq/ios-dev-agent/.cursor/rules/mvvm-architecture.mdc

ios-dev-agent / rules

Cursor rule4 starsChanged 6 months agoMITView on GitHub

iOS development rule

The file

We split this mvvm-architecture.mdc into the rules it gives an agent

12 rules. About 0 are common, 2 are distinctive, and 10 are very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈2

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 10

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Very specific:

    Every app that performs async operations MUST include this enum as Shared/Loadable.swift:

    line 11
  2. Very specific:

    Rule: All async operations MUST use Loadable<T> for state tracking — never use var isLoading: Bool + var errorMessage: String?

    line 38
  3. Distinctive:

    Every ViewModel follows this exact pattern:

    line 41
  4. Very specific:

    When a ViewModel loads data asynchronously, use Loadable<T> and start loading in init():

    line 69
  5. Very specific:

    Init Loading Rule: Use init() { Task { await load() } } for first data load.

    line 101
  6. Very specific:

    Use Loadable<T> for any property populated by async operations — never separate isLoading + error booleans

    line 108
  7. Very specific:

    Must NOT contain Views, UIView/UIViewController declarations, body, or #Preview

    line 110
  8. Very specific:

    NEVER: create a ViewModel inside a tab content view — SwiftUI recreates @State on every tab switch, causing data reloads.

    line 113
  9. Distinctive:

    Create all tab ViewModels at the MainView level and pass them down:

    line 115
  10. Very specific:

    Every view that displays async data MUST switch on ALL 4 Loadable cases:

    line 143
  11. Very specific:

    Never skip any case. Never use if let to unwrap only the success case.

    line 149
  12. Very specific:

    Every View file MUST include a #Preview block with sample data

    line 154

≈ “Common” is an estimate: at least 1 in 5 of the 6,668 Cursor rule files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
mvvm-architecture.mdc
---
description: iOS development rule
globs: "**/*.swift"
alwaysApply: true
---

# MVVM Architecture Rules

## Loadable Enum (Required for Async State)

Every app that performs async operations MUST include this enum as `Shared/Loadable.swift`:

```swift
// Shared/Loadable.swift
enum Loadable<T> {
    case notInitiated
    case loading
    case success(T)
    case failure(Error)

    var value: T? {
        if case .success(let v) = self { return v }
        return nil
    }

    var error: Error? {
        if case .failure(let e) = self { return e }
        return nil
    }

    var isLoading: Bool {
        if case .loading = self { return true }
        return false
    }
}
```

**Rule**: All async operations MUST use `Loadable<T>` for state tracking — never use `var isLoading: Bool` + `var errorMessage: String?`.

## ViewModel Pattern (In-Memory Default)
Every ViewModel follows this exact pattern:

```swift
import SwiftUI

@Observable
@MainActor
class NotesListViewModel {
    var notes: [Note] = Note.sampleData
    var searchText = ""

    var filteredNotes: [Note] {
        if searchText.isEmpty { return notes }
        return notes.filter { $0.title.localizedCaseInsensitiveContains(searchText) }
    }

    func addNote(title: String) {
        let note = Note(title: title)
        notes.insert(note, at: 0)
    }

    func deleteNote(_ note: Note) {
        notes.removeAll { $0.id == note.id }
    }
}
```

## ViewModel Pattern (Async Data)
When a ViewModel loads data asynchronously, use `Loadable<T>` and start loading in `init()`:

```swift
import SwiftUI

@Observable
@MainActor
class NotesListViewModel {
    var notes: Loadable<[Note]> = .loading  // Start as .loading — init fires immediately
    var searchText = ""

    init() {
        Task { await loadNotes() }
    }

    var filteredNotes: [Note] {
        guard let allNotes = notes.value else { return [] }
        if searchText.isEmpty { return allNotes }
        return allNotes.filter { $0.title.localizedCaseInsensitiveContains(searchText) }
    }

    func loadNotes() async {
        notes = .loading
        do {
            notes = .success(try await fetchNotes())
        } catch {
            notes = .failure(error)
        }
    }
}
```

**Init Loading Rule**: Use `init() { Task { await load() } }` for first data load. Do NOT use `.task` or `.onAppear` for initial loads — they fire on appear, not on creation, causing a flash of empty UI before data arrives.

## ViewModel Rules
- Annotate with `@Observable` and `@MainActor`
- ViewModel files contain **ONLY** the `@Observable` class — no other type declarations
- Handle business logic: CRUD, filtering, sorting, validation
- Initialize data arrays from model's `static sampleData` so app looks alive on first launch
- Use `Loadable<T>` for any property populated by async operations — never separate `isLoading` + `error` booleans
- May import `SwiftUI` and `UIKit` when needed for framework types, animation helpers, or required platform bridges
- Must NOT contain Views, `UIView`/`UIViewController` declarations, `body`, or `#Preview`

## Tab ViewModel Stability
**NEVER** create a ViewModel inside a tab content view — SwiftUI recreates `@State` on every tab switch, causing data reloads.

Create all tab ViewModels at the MainView level and pass them down:
```swift
struct MainView: View {
    @State private var roomsVM = RoomsViewModel()
    @State private var profileVM = ProfileViewModel()

    var body: some View {
        TabView {
            Tab("Rooms", systemImage: "bubble.left.and.bubble.right") {
                RoomsView(viewModel: roomsVM)
            }
            Tab("Profile", systemImage: "person") {
                ProfileView(viewModel: profileVM)
            }
        }
    }
}
```

Child tab views accept the ViewModel as a parameter:
```swift
struct RoomsView: View {
    var viewModel: RoomsViewModel
    var body: some View { ... }
}
```

## CRITICAL: Loadable State Handling
Every view that displays async data MUST `switch` on ALL 4 Loadable cases:
1. `.loading` → `ProgressView`
2. `.success(data)` where data is empty → `ContentUnavailableView` with action
3. `.success(data)` → content view
4. `.failure(error)` → error view with retry button

Never skip any case. Never use `if let` to unwrap only the success case.

## View Responsibilities
- Views own `@State` for **local UI state** (sheet presented, text field binding, animation flags)
- Views reference ViewModels via `@State var viewModel = SomeViewModel()` (or accept as parameter in tab views)
- Every View file **MUST** include a `#Preview` block with sample data

## Data Access Patterns
| What | Where | How |
|------|-------|-----|
| App data (default) | ViewModel | In-memory arrays initialized from sampleData |
| Async data | ViewModel | `Loadable<T>` enum — `.notInitiated` → `.loading` → `.success(T)` / `.failure(Error)` |
| Simple flags/settings | View or ViewModel | `@AppStorage` |
| Transient UI state | View | `@State` |
| Persistent data (only if user asks) | ViewModel | SwiftData `@Query` / `modelContext` |

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.