How to use ForEach on a NSSet generated by CoreData in SwiftUI

4.9k Views Asked by At

I generated a CoreData model with some 1-to-many relationships. Now I want to use a ForEach on this relationship which is a NSSet, then I'm getting the following error:

Generic struct 'ForEach' requires that 'NSSet' conform to 'RandomAccessCollection'

My code looks like this:

struct DetailView: View {
    var sample: Sample

    var body: some View {
        VStack {
            ForEach(sample.stepps!, id: \.self) { step in
                ...
            }
        }
    }
}

How to solve this?

2

There are 2 best solutions below

3
Asperi On BEST ANSWER

Here is possible approach

ForEach(Array(sample.stepps! as Set), id: \.self) { step in
    // step is NSObject type, so you'll need it cast to your model
}
1
Sifan On
if let steps = sample.steps?.allObjects as? [Step] {
  ForEach(steps) {step in
    Text("\(step.title ?? "step")")
  }
}