I am getting the error: "Generic struct 'ForEach' requires that 'Set' conform to 'RandomAccessCollection'" when trying to display items I have selected from a list in another view.
import SwiftUI
struct ExSetView: View {
@Environment(\.managedObjectContext) var viewContext
@Environment(\.dismiss) var dismiss
@State var selectedItems = Set<Exercise>()
var body: some View {
NavigationView {
VStack (alignment: .leading) {
Text("Set Count: \(selectedItems.count)")
ForEach(selectedItems) { e in
NavigationLink(
destination: ExSetInputView(exset: e),
label: {
Text(e.exercisename)
}
)}
}
}
}
}
The error is on the line ForEach(selectedItems) { e in
I have no clue how to fix this. Ultimately I just want to display the selected items by their property of exercisename as a navigation link. Is there another way without using For Each? Is the issue because it is a set and not an array? Any help would be greatly appreciated!!!!
CodePudding user response:
ForEach
requires an ordered data source, a Set
is unordered by definition.
A simple solution is to sort the Set for example by exercisename
ForEach(selectedItems.sorted{$0.exercisename < $1.exercisename})
The result of sorted
is an array which is 'RandomAccessCollection
compliant.