swiftcore-dataswiftuinsorderedset

How to ForEach in SwiftUI a NSOrderedSet from FetchedResults (CoreData)


I am trying to use ForEach in SwiftUI with my NSOrderedSet with comes from a FetchedResult. Tried already the following code (from this response)

withChilds is a relationship definied (Core Data - one Card has many childs).

In Card:

@NSManaged public var withChilds: NSOrderedSet?

My View Code

struct Test: View {
        @FetchRequest(entity: Card.entity(),
                  sortDescriptors: [],
                  predicate: nil)
    var cards: FetchedResults<Card>

    var body: some View {

        VStack {

            Text("count: \(cards[0].withChilds?.count)") //first entity on purpose

            ScrollView {
                ForEach(cards){  card in
                    ForEach(Array(card.withChilds!.set), id: \.self) { child in //**ERROR**
                        //Text("someText: \(child.text1)")
                    }   
                }
            }
        }
    }
}

Error code enter image description here


Solution

  • The highlighted error is because there is no view specified in ForEach, so if to define something static, like

    ForEach(Array(card.withChilds!.set), id: \.self) { child in 
            Text("Just test")
        }   
    

    there should be no error (tested with Xcode 11.4)

    But there is no specified what is inside that NSOrderedSet, so if suppose it is instances of Child class then the following tested works

    ForEach(Array(card.withChilds!.set), id: \.self) { child in 
            Text("someText: \((child as! Child).text1)")
        }