iOS Development

ios – SwiftData – Making a #Predicate with optionally available one to many relationship leads to FatalError Thread 1: “to-many key not allowed right here”

Spread the love


I have not 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 with a purpose to work with CloudKit. I’ve recreated this with a quite simple mission. Let’s assume I am on the lookout for a dad and mom with a child by the title of ‘Abbijean’.

Mannequin.swift

@Mannequin
class Mother or father {
    let identifier: UUID
    let title: String
    @Relationship(deleteRule: .cascade, inverse: Child.father or mother) var youngsters: [Kid]?
    init( title: String, youngsters: [Kid]? = nil) {
        self.identifier = UUID()
        self.title = title
    }
}

@Mannequin
class Child {
    let identifier: UUID
    let title: String
    var father or mother: Mother or father?
    init(title: String, father or mother: Mother or father? = nil) {
        self.identifier = UUID()
        self.title = title
    }
}

ContentView.swift

struct ContentView: View {
    @Setting(.modelContext) var modelContext
    @Question(filter: #Predicate<Mother or father> { father or mother in
//        father or mother.youngsters?.incorporates(the place: {
//            $0.title == "Abbiejean"
//        }) != nil
        father or mother.youngsters.flatMap { youngsters in
            youngsters.incorporates(the place: { $0.title == "Abbijean" })
        } == true

    }) var dad and mom: [Parent]
    var physique: some View {
        Button(motion: {
            var parent1 = Mother or father(title: "Sterling Archer")
            parent1.youngsters?.append(Child(title: "Abbiejean"))
            modelContext.insert(parent1)
        }, label: {
            Textual content("Add Knowledge")
        })
        Record {
            ForEach(dad and mom, id: .id) { father or mother in
                Textual content("(father or mother.title)")
            }
        }
    }
}

When utilizing:

father or mother.youngsters?.incorporates(the place: {
   $0.title == "Abbiejean"
}) != nil

The compiler tells me to make use of a flatMap when unwrapping optionals

Utilizing a flat map:

father or mother.youngsters.flatMap { youngsters in
    youngsters.incorporates(the place: { $0.title == "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)

Leave a Reply

Your email address will not be published. Required fields are marked *