惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

AWS News Blog
AWS News Blog
Schneier on Security
Schneier on Security
P
Palo Alto Networks Blog
T
Threat Research - Cisco Blogs
NISL@THU
NISL@THU
S
Secure Thoughts
L
LINUX DO - 最新话题
S
Securelist
C
CXSECURITY Database RSS Feed - CXSecurity.com
C
Cybersecurity and Infrastructure Security Agency CISA
Recent Announcements
Recent Announcements
S
Schneier on Security
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
T
Tailwind CSS Blog
Application and Cybersecurity Blog
Application and Cybersecurity Blog
Cyberwarzone
Cyberwarzone
宝玉的分享
宝玉的分享
Last Week in AI
Last Week in AI
月光博客
月光博客
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
酷 壳 – CoolShell
酷 壳 – CoolShell
雷峰网
雷峰网
Security Archives - TechRepublic
Security Archives - TechRepublic
V
Vulnerabilities – Threatpost
T
Tor Project blog
GbyAI
GbyAI
B
Blog
博客园 - 司徒正美
博客园 - 叶小钗
Recorded Future
Recorded Future
F
Fortinet All Blogs
Spread Privacy
Spread Privacy
IT之家
IT之家
Forbes - Security
Forbes - Security
L
Lohrmann on Cybersecurity
有赞技术团队
有赞技术团队
博客园 - 聂微东
A
Arctic Wolf
D
Darknet – Hacking Tools, Hacker News & Cyber Security
T
The Blog of Author Tim Ferriss
N
News and Events Feed by Topic
O
OpenAI News
Apple Machine Learning Research
Apple Machine Learning Research
Help Net Security
Help Net Security
Martin Fowler
Martin Fowler
WordPress大学
WordPress大学
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
TaoSecurity Blog
TaoSecurity Blog
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Room-Inspired Local Persistence in Swift: A Production GRDB Architecture
Hakim · 2026-06-16 · via DEV Community

Introduction

If you've built Android apps with Room, you already think in a layered persistence model: entities define your schema, DAOs handle queries, repositories abstract the data layer, and ViewModels stay completely ignorant of the database. It's clean, testable, and scalable.

When you cross to iOS and reach for local persistence, you hit a wall. Core Data is powerful but infamous for its boilerplate and threading pitfalls. SwiftData is promising but young. GRDB (a Swift SQLite toolkit) is arguably the best option available today: fast, type-safe, well-maintained, and built around Swift concurrency. However, it ships with no official architecture pattern. The documentation shows you the API but doesn't tell you how to structure a real app.

This tutorial fills that gap. We'll build a production-ready GRDB architecture from scratch, layer by layer, using the same mental model Room developers already know: entity → DAO → repository → ViewModel. By the end, your ViewModel will read and write data with a single async call, with no GRDB imports, no threading concerns, and no setup boilerplate at the call site.

Here's what we'll build:

  • A MyDataBase singleton that owns the connection and exposes all DAOs
  • A MyEntity that handles its own schema, migration, and non-primitive type encoding
  • A MyDao with clean reader/writer separation
  • A MyRepositoryImpl as the single data entry point
  • A ViewModel that calls the repository as if persistence doesn't exist

Setting Up the Database MyDatabase

The foundation of the entire architecture is a single file: MyDatabase.swift. This is the equivalent of Room's RoomDatabase subclass. It owns the connection, runs migrations, and exposes every DAO. Everything else in the stack depends on it.

Creating the database file

GRDB connects to SQLite through a DatabasePool—the right choice for any production app because it allows multiple concurrent reads while serializing writes. We point it at the app's Application Support directory, which is the correct location for user-generated data on iOS (it is not visible to the user and is backed up by iCloud by default).

struct MyDatabase {
  let writer: DatabaseWriter

  init(_ writer: DatabaseWriter) throws {
        self.writer = writer
        try migrator.migrate(writer)
   }

   var reader: DatabaseReader {
        writer
    }
}

Two things worth noting here. First, writer is typed as DatabaseWriter and reader as a DatabaseReader which are GRDB protocols, not concrete types. This matters for testing: you can swap DatabasePool for an in-memory DatabaseQueue without changing any downstream code. Second reader simply returns writer. DatabasePool conforms to both protocols, so this costs nothing while keeping the read/write intent explicit at every call site.

The shared singleton

extension MyDatabase {
   static let shared = createShared()

   static func createShared() -> MyDatabase {
     do {
         let fileManager = FileManager()
         let folder = try fileManager.url(
             for: .applicationSupportDirectory,
             in: .userDomainMask,
             appropriateFor: nil,
             create: true
          ).appendingPathComponent("database", isDirectory:true)

          try fileManager.createDirectory(at: folder, withIntermediateDirectories: true)
          let databaseURL = folder.appendingPathComponent("yourAppName.sqlite")
          let writer = try DatabasePool(path: databaseURL.path)
          return try MyDatabase(writer)
      }
      catch{
          fatalError(error.localizedDescription)
        }
   }
}

The fatalError on failure is intentional. If the database cannot be created at launch, the app has no recoverable state, failing loudly is the right call here, and it mirrors what Room does under the hood when misconfigured.

Registering the DAOs

Once the shared instance exists, DAOs are registered as static properties on MyDatabase itself:

extension MyDatabase {
    static let myDao = MyDao(
        reader: shared.reader,
        writer: shared.writer
    )
}

This means any layer of the app can access MyDatabase.myDao without passing the database instance around. We'll build the DAO itself in part 5. For now, think of these static properties as the switchboard that connects the database connection to every data access object in the app.

Defining an Entity MyEntity

In Room, an entity is a data class annotated with @Entity. GRDB's equivalent is a Swift struct that conforms to two protocols:FetchableRecord for reading rows from the database, and PersistableRecord for writing them back. Add Codable to get serialization for primitive fields.

struct MyEntity: Codable, FetchableRecord, PersistableRecord {
    let userId: String
    let rating: Double
    let photos: [String]
    let city: [String: String]

    static let databaseTableName = "MyEntity"

    static let persistenceConflictPolicy = PersistenceConflictPolicy(
        insert: .replace
    )
}

databaseTableName maps the struct to its SQLite table — GRDB's equivalent of Room's tableName parameter. persistenceConflictPolicy set to .replace means any insert on an existing primary key silently upserts rather than throwing. This is the right default for a cache that syncs from a remote source: you always want the latest data to win.

Type-safe column references

Rather than scattering raw string literals across queries, we declare columns once as a nested enum:

public enum Columns {
    static let userId = Column("userId")
    static let rating = Column("rating")
    static let photos = Column("photos")
    static let city = Column("city")
}

Column is a GRDB type that participates in the query builder. Referencing Columns.userId instead of "userId" everywhere means a rename is a single change.

Handling non-primitive types

This is where GRDB diverges from Room and requires explicit handling. SQLite has no native type for [String] or [Sting: String] everything must be stored as text, integer, real, or blob. Room handles this with @TypeConverter; GRDB leaves it to you.

The solution is to JSON-encode complex types on write and decode them on read:

extension MyEntity {
  static func encodeDictionary(_ dict: [String: String]) throws -> String {
        let data = try JSONEncoder().encode(dict)
        return String(data: data, encoding: .utf8) ?? "{}"
    }

  static func decodeDictionary(_ string: String) throws -> [String: String] {
        guard let data = string.data(using: .utf8) else { return [:] }
        return try JSONDecoder().decode([String: String].self, from: data)
    }

  static func encodeArray(_ array: [String]) throws -> String {
        let data = try JSONEncoder().encode(array)
        return String(data: data, encoding: .utf8) ?? "[]"
    }

  static func decodeArray(_ string: String) throws -> [String] {
        guard let data = string.data(using: .utf8) else { return [] }
        return try JSONDecoder().decode([String].self, from: data)
    }
}

These helpers are static on the entity itself, the same place Room developers would put a TypeConverter companion. They're called inside the two protocol methods that GRDB requires you to implement manually when your type has non-primitive fields.

Writing to the database encode(to:)

extension MyEntity {
  public func encode(to container: inout PersistenceContainer) throws {
  container[Columns.userId] = userId
  container[Columns.rating] = rating

  container[Columns.photos] = try MyEntity.encodeArray(photos)
  container[Columns.city] = try MyEntity.encodeDictionary(city) 
  }
}

Primitive fields are assigned directly. Non-primitive fields go through the encode helpers first. GRDB calls this method automatically on every write; you never call it yourself.

Reading from the database — init(row:)

extension MyEntity {
  public init(row: Row) throws {
    userId = row[Columns.userId]
    rating = row[Columns.rating]

        photos = try MyEntity.decodeArray(row[Columns.photos])
        city = try MyEntity.decodeDictionary(row[Columns.city])
  }
}

The mirror image of encode. GRDB calls this whenever it materializes a row into your type — fetchAll, fetchOne, anywhere. The decode helpers reverse exactly what encode wrote.

Owning the schema

The last piece is createTable, which lives as a static method on the entity itself:

static func createTable(_ db: Database) throws {
  try db.create(table: databaseTableName) { t in
    t.column(Columns.userId.name, .text).primaryKey()
    t.column(Columns.rating.name, .text).notNull()
    t.column(Columns.photos.name, .text).notNull()
    t.column(Columns.city.name, .text).notNull()
  }
}

Keeping createTable on the entity means the schema definition and the type that represents it live in the same file. When you add a column, you update the struct, the Columns enum, the encode/decode methods, and the table definition all in one place — the same discipline Room enforces through its annotation processor.

Migrations — DatabaseMigrator

In Room, migrations are defined as Migration objects passed to the database builder. GRDB's equivalent is DatabaseMigrator — a value type you configure with named migration blocks, then run against the database connection. The key property that makes it production-safe is that each migration runs exactly once, identified by its name. GRDB tracks which migrations have already been applied and skips them on subsequent launches.

We add the migrator as a computed property on MyDatabase:

extension MyDatabase {
  var migrator: DatabaseMigrator {
    var migrator = DatabaseMigrator()

    #if DEBUG
    migrator.eraseDatabaseOnSchemaChange = true
    #endif

    migrator.registerMigration("v1") { db in
     try MyEntity.createTable(db)

    }
    return migrator

  }
}

This is called in the MyDatabase initializer we wrote in part 2:

init(_ writer: DatabaseWriter) throws {
    self.writer = writer
    try migrator.migrate(writer)
}

So by the time MyDatabase.shared is ready, the schema is guaranteed to exist.

Adding future migrations

When your schema needs to change after shipping, you register a new named block alongside the existing one:

migrator.registerMigration("v1") { db in
    // original schema — never touch this
}

migrator.registerMigration("v2") { db in
    try db.alter(table: "MyEntity") { t in
        t.add(column: "age", .text)
    }
}

The names are the contract. GRDB stores them in a internal grdb_migrations table and uses them to determine what has and hasn't run. Renaming a migration that has already shipped is the same as deleting it — GRDB will try to run it again on existing installs and likely fail. Treat migration names as append-only.

The DAO Layer — MyDao

In Room, a DAO is an interface annotated with @Dao — Room generates the implementation for you at compile time. In GRDB there's no code generation, so the DAO is a plain Swift class you write yourself. The pattern is the same: one class, one entity, all database access for that entity goes through it and nowhere else.

Constructor injection of reader and writer

class MyDao {
    private let reader: DatabaseReader
    private let writer: DatabaseWriter

    init(reader: DatabaseReader, writer: DatabaseWriter) {
        self.reader = reader
        self.writer = writer
    }
}

This is the most important structural decision in the DAO. By accepting DatabaseReader and DatabaseWriter as protocols rather than a concrete DatabasePool, the DAO is completely decoupled from the database setup. In tests you pass an in-memory DatabaseQueue; in production you pass the shared DatabasePool. The DAO itself never knows the difference.

The separation also enforces intent at every method signature. If a method takes only reader, it provably cannot write. If it takes only writer, it provably cannot run a read on the wrong connection. This is the threading discipline GRDB is designed around.

Read operations

func getSingleUser(_ userId: String) async throws -> MyEntity? {
    return try await reader.read { db in
        try MyEntity.fetchOne(db, sql: "SELECT * FROM MyEntity WHERE userId = ?", arguments: [userId])
    }
}

func getAllAvailableUsers() async throws -> [MyEntity] {
    return try await reader.read { db in
        try MyEntity.fetchAll(db)
    }
}

reader.read schedules the closure on GRDB's internal reader queue — concurrent with other reads, never blocking writes. The async/await surface means the call site looks like any other async Swift function. There are no completion handlers, no DispatchQueue juggling, no @escaping closures to reason about.

fetchOne returns an optional — nil if no row matches. fetchAll returns an empty array if the table is empty. Neither throws on an empty result, only on a genuine database error. That distinction matters when you're deciding whether to show an empty state or an error state in the UI.

Write operations

func insertUsers(_ usersList: [MyEntity]) async throws {
    try await writer.write { db in
        for user in usersList {
            try user.save(db, onConflict: .replace)
        }
    }
}

func deleteAllUsers() async throws {
    try await writer.write { db in
        try MyEntity.deleteAll(db)
    }
}

func updateUsers(_ usersList: [MyEntity]) async throws {
    try await writer.write { db in
        try MyEntity.deleteAll(db)
        for user in usersList {
            try user.save(db, onConflict: .replace)
        }
    }
}

writer.write serializes the closure — only one write runs at a time, always. Everything inside a single write block is an atomic transaction: if any operation throws, the entire block rolls back automatically. This is why updateUsers deletes all rows and reinserts in the same block — either both operations succeed together or neither does. You never end up with a half-replaced dataset.

save(onConflict: .replace) is a per-call override that works alongside the entity-level persistenceConflictPolicy we set in part 3. They do the same thing here — but spelling it out at the call site makes the intent explicit to anyone reading the DAO later.

Registering the DAO on MyDatabase

Back in MyDatabase, we wire everything together:

extension MyDatabase {
    static let myDao = MyDao(
        reader: shared.reader,
        writer: shared.writer
    )
}

From this point forward, nothing in the app ever instantiates MyDao directly or touches a DatabaseReader or DatabaseWriter outside of this file. The DAO is the last layer that knows GRDB exists.

The pattern is identical for every other entity — UserDao, ChatDao, FilterDao, AnyDao — same constructor, same reader/writer split, same async throws surface. That's the payoff of the architecture: adding a new entity is mechanical.

The Repository Layer — MyRepositoryImpl

If the DAO is the last layer that knows GRDB exists, the repository is the first layer that doesn't. Its job is simple: receive calls from the ViewModel, delegate to the DAO, and return results. No database logic, no SQL, no GRDB imports visible to anything above it.

class MyRepositoryImpl {
    private let myDao: MyDao

    init(db: MyDatabase = .shared) {
        self.myDao = MyDatabase.myDao
    }
}

The default argument db: MyDatabase = .shared means the ViewModel can instantiate the repository with no arguments in production, while tests can pass an alternative database instance. The repository itself never holds a reference to the database — only to the DAO it needs.

Delegating reads

func getSingleUser(userId: String) async throws -> MyEntity? {
    return try await myDao.getSingleUser(userId)
}

func getAllAvailableUsers() async throws -> [MyEntity] {
    return try await myDao.getAllAvailableUsers()
}

These are pure pass-throughs and that's intentional. The repository's value isn't in transforming data at this layer — it's in being the seam where you could add caching, logging, or remote fallback later without the ViewModel ever knowing. Today it delegates; tomorrow it could check a remote source first and fall back to local. The ViewModel call site doesn't change either way.

Delegating writes

func replaceUsers(usersList: [MyEntity]) async throws {
    try await myDao.updateUsers(usersList)
}

func insertUsers(usersList: [MyEntity]) async throws {
    try await myDao.insertUsers(usersList)
}

func deleteAllUsers() async throws {
    try await myDao.deleteAllUsers()
}

Notice the method names are business-language rather than database-language. The ViewModel calls replaceUsers — it doesn't need to know that "replace" means delete-all then reinsert inside an atomic write block. That translation lives in the DAO. The repository just gives it a name the rest of the app can reason about.

Error handling strategy

Every method here is async throws. The repository does not swallow errors — it lets them propagate up to the ViewModel, which is the right place to decide what to show the user. The one exception is methods where a missing result is a valid state rather than an error:

func getAllUsers() async -> [MyEntity]? {
    do {
        return try await myDao.getAllAvailableUsers()
    } catch {
        return nil
    }
}

This is a deliberate choice — returning nil here signals "something went wrong, show nothing" without forcing the ViewModel into a catch block for a non-critical read. Use it sparingly. For anything where the error should change UI state, let it throw.

Wiring to a ViewModel

This is where the architecture pays off. The ViewModel sits at the top of the stack and knows nothing below the repository. No GRDB imports, no database references, no threading setup. Just an async call and a state update.

The ViewModel

@MainActor
class MyViewModel: ObservableObject {
    @Published var user: MyEntity?
    @Published var isLoading: Bool = false
    @Published var error: Error?

    private let userId: String
    private let myRepository: MyRepositoryImpl

    init(
        userId: String,
        myRepository: MyRepositoryImpl = MyRepositoryImpl()
    ) {
        self.userId = userId
        self.myRepository = myRepository
    }
}

@MainActor is the key annotation here. It guarantees every property update happens on the main thread automatically — no DispatchQueue.main.async wrappers, no await MainActor.run blocks scattered through the code. Swift enforces this at compile time. Combined with @Published, any state change the ViewModel makes is immediately safe to consume in a SwiftUI view.

The repository has a default argument in the initializer — in production SwiftUI previews and the app itself pass nothing, in tests you inject a repository backed by an in-memory database.

Reading data

extension MyViewModel {
    func fetchUser() async {
        isLoading = true
        defer { isLoading = false }
        do {
            user = try await myRepository.getSingleUser(
                userId: userId
            )
        } catch {
            self.error = error
        }
    }

    func fetchAllusers() async -> [MyEntity] {
        do {
            return try await myRepository.getAllAvailableUsers()
        } catch {
            self.error = error
            return []
        }
    }
}

Writing data

extension MyViewModel {
    func saveUsers(_ users: [MyEntity]) async {
        do {
            try await myRepository.replaceUsers(usersList: users)
        } catch {
            self.error = error
        }
    }

    func clearUsers() async {
        do {
            try await myRepository.deleteAllUsers()
            user = nil
        } catch {
            self.error = error
        }
    }
}

Consuming in a SwiftUI view

struct MyView: View {
    @StateObject var viewModel: MyViewModel

    var body: some View {
        Group {
            if viewModel.isLoading {
                ProgressView()
            } else if let user = viewModel.user {
                VStack(alignment: .leading) {
                    Text(user.userId)
                        .font(.headline)
                }
            } else {
                Text("No user found")
            }
        }
        .onAppear{
            Task{ await viewModel.fetchUser() }
        }
    }
}

Wrapping Up

Each layer has exactly one job and depends only on the layer below it. Adding a new entity means creating a new Entity, Dao, and RepositoryImpl following the same pattern — the rest of the stack stays untouched.

If you've built with Room on Android, this architecture will feel familiar. The layers and the separation of concerns translate naturally across platforms — GRDB gives you the same discipline, just in Swift.