import Foundation import SwiftData import SwiftUI /// 书架:与书籍是一对多关系,删除书架级联删除书籍。 @Model public final class Shelf { public var name: String public var createdAt: Date @Relationship(deleteRule: .cascade, inverse: \Book.shelf) public var books: [Book] = [] public init(name: String, createdAt: Date = .init(timeIntervalSince1970: 0)) { self.name = name self.createdAt = createdAt } } /// 书籍:`@Model` 生成最终类,属性变化会被持久化追踪。 @Model public final class Book { public var title: String public var author: String public var createdAt: Date public var shelf: Shelf? public init( title: String, author: String, createdAt: Date = .init(timeIntervalSince1970: 0), shelf: Shelf? = nil ) { self.title = title self.author = author self.createdAt = createdAt self.shelf = shelf } } /// 数据访问层:只依赖 `ModelContext`,便于在内存容器里测试。 public enum Library { public static func makeContainer(inMemory: Bool = true) throws -> ModelContainer { let configuration = ModelConfiguration(isStoredInMemoryOnly: inMemory) return try ModelContainer(for: Shelf.self, Book.self, configurations: configuration) } public static func addBook( title: String, author: String, to shelf: Shelf?, in context: ModelContext ) -> Book { let book = Book(title: title, author: author, shelf: shelf) context.insert(book) return book } public static func books(in context: ModelContext) throws -> [Book] { let descriptor = FetchDescriptor( sortBy: [SortDescriptor(\.title), SortDescriptor(\.author)] ) return try context.fetch(descriptor) } public static func shelves(in context: ModelContext) throws -> [Shelf] { let descriptor = FetchDescriptor(sortBy: [SortDescriptor(\.name)]) return try context.fetch(descriptor) } public static func delete(_ shelf: Shelf, in context: ModelContext) { context.delete(shelf) } public static func save(_ context: ModelContext) throws { try context.save() } } /// 截图:静态书架板,避免 `@Query` 依赖容器。 public struct LibraryBoard: View { public init() {} public var body: some View { VStack(alignment: .leading, spacing: 12) { Text("SwiftData") .font(.system(size: 18, weight: .semibold)) row("模型", "@Model final class,引用语义") row("容器", "ModelContainer(内存 / 磁盘)") row("查询", "@Query 或 FetchDescriptor") row("关系", "@Relationship + deleteRule") row("迁移", "VersionedSchema + MigrationPlan") } .padding(18) .frame(width: 360, alignment: .leading) .background(Color.white) } private func row(_ title: String, _ detail: String) -> some View { HStack(spacing: 10) { Text(title) .font(.system(size: 11, design: .monospaced)) .frame(width: 56, alignment: .leading) Text(detail) .font(.system(size: 11)) .foregroundStyle(.secondary) Spacer() } } }