I tried to practice SwiftData by creating a LinkedList. However, contrary to my expectations.
even though a.next == b
but b.next != nil, b.next == a. Why is that?
@Environment(\.modelContext) private var modelContext
@Query private var items: [Item]
Button {
var a = Item(value: 0)
var b = Item(value: 1)
a.next = b
modelContext.insert(a)
} label: {
Text("+++")
}
@Model
final class Item {
var value: Int
weak var next: Item?
init(value: Int, next: Item? = nil) {
self.value = value
self.next = next
}
}
this is whole code
import SwiftUI
import SwiftData
struct ContentView: View {
@Environment(\.modelContext) private var modelContext
@Query private var items: [Item]
var body: some View {
ZStack {
VStack {
ForEach(items){item in
Button {
modelContext.delete(item)
} label: {
Text(String(item.value))
}
}
}
}
VStack {
Button {
var a = Item(value: 0)
var b = Item(value: 1)
a.next = b
modelContext.insert(a)
// modelContext.insert(b)
// let fetch = FetchDescriptor<Item>(
// predicate: #Predicate{$0.value == 0}
// )
// let data = try! modelContext.fetch(fetch)
// data[0].next = b
} label: {
Text("+++")
}
Button {
for i in items {
modelContext.delete(i)
}
} label: {
Text("---")
}
Button {
for i in items {
print(i.value)
print(i.next)
}
} label: {
Text("Print")
}
}
}
}
#Preview {
ContentView()
.modelContainer(for: Item.self, inMemory: true)
}