import AppKit import Ch42Kit import SwiftData import SwiftUI @main struct Ch42Demo { @MainActor static func main() { do { let container = try Library.makeContainer() let context = ModelContext(container) let shelf = Shelf(name: "语言") context.insert(shelf) _ = Library.addBook(title: "Swift", author: "Apple", to: shelf, in: context) _ = Library.addBook(title: "C++", author: "Stroustrup", to: shelf, in: context) _ = Library.addBook(title: "Go", author: "Pike", to: nil, in: context) try Library.save(context) let books = try Library.books(in: context) print("[42.1] 书籍数量 = \(books.count)") print("[42.2] 排序后标题 = \(books.map(\.title).joined(separator: ","))") print("[42.3] 书架内书籍 = \(shelf.books.count)") Library.delete(shelf, in: context) try Library.save(context) print("[42.4] 删除书架后书籍 = \(try Library.books(in: context).count)") print("[42.5] 书架数量 = \(try Library.shelves(in: context).count)") } catch { print("[42.0] SwiftData 失败 = \(error)") } print("[42.6] 板渲染 = \(size(LibraryBoard()))") print("[42.7] MemoryLayout = \(MemoryLayout.size) 字节") if let directory = ProcessInfo.processInfo.environment["SHOTS_DIR"] { write(LibraryBoard(), name: "swiftdata-board.png", directory: directory) } } @MainActor private static func size(_ view: some View) -> String { guard let image = ImageRenderer(content: view).cgImage else { return "nil" } return "\(image.width)x\(image.height)" } @MainActor private static func write(_ view: some View, name: String, directory: String) { let renderer = ImageRenderer(content: view) renderer.scale = 2 guard let image = renderer.cgImage, let data = NSBitmapImageRep(cgImage: image).representation(using: .png, properties: [:]) else { print("[42.8] 截图失败:\(name)") return } let url = URL(fileURLWithPath: directory).appendingPathComponent(name) do { try FileManager.default.createDirectory( at: url.deletingLastPathComponent(), withIntermediateDirectories: true ) try data.write(to: url) print("[42.8] 截图 = \(name) \(image.width)x\(image.height)") } catch { print("[42.8] 截图失败:\(error)") } } }