Skip to content

Instantly share code, notes, and snippets.

@nickretallack
Last active July 16, 2024 05:23
Show Gist options
  • Save nickretallack/da7cac45c838ead0997657166d1ebc94 to your computer and use it in GitHub Desktop.
Save nickretallack/da7cac45c838ead0997657166d1ebc94 to your computer and use it in GitHub Desktop.
Example of using relationships in a SwiftData preview and passing an instance as an argument.
import SwiftUI
import SwiftData
struct ItemView: View {
var parent: Parent
var body: some View {
VStack {
Text(parent.id)
List(parent.children) { child in
Text("Child \"\(child.id)\" of parent \"\(child.parent!.id)\"")
}
}
}
}
#Preview {
// create a container
let schema = Schema([Parent.self, Child.self])
let config = ModelConfiguration(isStoredInMemoryOnly: true)
let container = try! ModelContainer(for: schema, configurations: config)
// add data
let parent = Parent(id: "sup")
container.mainContext.insert(parent) // always insert the parent before associating a child
let child = Child(id: "yooooo")
parent.children.append(child)
// save. Not necessary but it helps sometimes
try! container.mainContext.save()
return ItemView(parent: parent)
.modelContainer(container) // don't need a model container in this example but you can pass one anyway
}
@Model
final class Parent {
@Attribute(.unique) var id: String
public var children: [Child] = []
init(id: String) {
self.id = id
}
}
@Model
final class Child {
@Attribute(.unique) var id: String
var parent: Parent? // parent must be optional or swiftdata won't work. Seems like a bug.
init(id: String, parent: Parent? = .none) {
self.id = id
self.parent = parent
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment