🐱
【備忘録】SwiftData Preview用のサンプルデータの作り方
前提
@Modelを付与したParent, Childを定義します。これらのModelは1:Nの関係になっています。
Parent.swift
@Model
final class Parent {
var name: String
@Relationship(deleteRule: .cascade, inverse: \Child.parent)
var child: [Child] = []
init(name: String) {
self.name = name
}
}
Child.swift
@Model
final class Child {
var name: String
var parent: Parent?
init(name: String, parent: Parent) {
self.name = name
self.parent = parent
}
}
Preview用のサンプルデータを作る
まずは自作のサンプルデータを含むModelContainerを定義します。
SampleData.swift
@MainActor
class SampleData {
static let previewContainer: ModelContainer = {
do {
let config = ModelConfiguration(isStoredInMemoryOnly: true)
let container = try ModelContainer(
for: Parent.self, Child.self,
configurations: config
)
let parents = [Parent(name: "🐱"), Parent(name: "🐶"), Parent(name: "🐧")]
for i in parents {
container.mainContext.insert(i)
}
for i in 0..<10 {
let child = Child(
name: "child\(i)",
parent: parents[Int.random(in: 0..<parents.count)]
)
container.mainContext.insert(child)
}
return container
} catch {
fatalError("Failed to create model container for previewing: \(error.localizedDescription)")
}
}()
}
そして、今作ったサンプルデータを.modelContainer()
にぶち込みます🧚♀️
ContentView.swift
#Preview {
ContentView()
.modelContainer(SampleData.previewContainer)
}
無事、Previewにサンプルデータが反映されています。
ContentView全体コード
ContentView.swift
import SwiftUI
import SwiftData
struct ContentView: View {
@Query var parents: [Parent]
var body: some View {
VStack {
ForEach(parents) { parent in
Text(parent.name)
HStack {
ForEach(parent.child) { child in
Text(child.name)
}
}
Divider()
}
}
.padding()
}
}
#Preview {
ContentView()
.modelContainer(SampleData.previewContainer)
}
参考文献
How to use SwiftData in SwiftUI previews:
Discussion