[ad_1]
I have never been capable of finding an answer to a predicate that filters on an optionally available one to many relationship. The connection must be optionally available to be able to work with CloudKit. I’ve recreated this with a quite simple challenge. Let’s assume I am on the lookout for a mother and father with a child by the identify of ‘Abbijean’.
Mannequin.swift
@Mannequin
class Father or mother {
let identifier: UUID
let identify: String
@Relationship(deleteRule: .cascade, inverse: Child.guardian) var youngsters: [Kid]?
init( identify: String, youngsters: [Kid]? = nil) {
self.identifier = UUID()
self.identify = identify
}
}
@Mannequin
class Child {
let identifier: UUID
let identify: String
var guardian: Father or mother?
init(identify: String, guardian: Father or mother? = nil) {
self.identifier = UUID()
self.identify = identify
}
}
ContentView.swift
struct ContentView: View {
@Setting(.modelContext) var modelContext
@Question(filter: #Predicate<Father or mother> { guardian in
// guardian.youngsters?.accommodates(the place: {
// $0.identify == "Abbiejean"
// }) != nil
guardian.youngsters.flatMap { youngsters in
youngsters.accommodates(the place: { $0.identify == "Abbijean" })
} == true
}) var mother and father: [Parent]
var physique: some View {
Button(motion: {
var parent1 = Father or mother(identify: "Sterling Archer")
parent1.youngsters?.append(Child(identify: "Abbiejean"))
modelContext.insert(parent1)
}, label: {
Textual content("Add Knowledge")
})
Record {
ForEach(mother and father, id: .id) { guardian in
Textual content("(guardian.identify)")
}
}
}
}
When utilizing:
guardian.youngsters?.accommodates(the place: {
$0.identify == "Abbiejean"
}) != nil
The compiler tells me to make use of a flatMap when unwrapping optionals
Utilizing a flat map:
guardian.youngsters.flatMap { youngsters in
youngsters.accommodates(the place: { $0.identify == "Abbijean" })
} == true
The app crashes with: Thread 1: “to-many key not allowed right here”
Examined in Xcode 15.0.1 (iOS 17.0.1) and 15 Beta 3 (iOS 17.2)
[ad_2]