I'm building a UI with SwiftUI, and I have an array that I use to build a List
element. Now I want to sort that list based on a @Published
variable coming from an @EnvironmentObject
.
Approach 1
I tried getting the array already sorted, passing in the environment object to the sorting method:
List(getArraySorted(environmentObject)) { item in
//do stuff with item
}
This will compile, but the list will not update if environmentObject
changes. I also tried passing in environmentObject.variableToBaseSortOn
but to no avail.
Approach 2
I tried sorting the array inline in Swift UI:
List(array.sorted(by: { (lhs, rhs) -> Bool in
// do sorting based on self.environmentObject
})) { item in
// do stuff with item
}
This will compile, but crash:
Fatal error: No ObservableObject of type EnvironmentObjectClass found.
A View.environmentObject(_:) for EnvironmentObjectClass may be missing as an ancestor of this view.
The hint in the crash is incorrect, environmentObject
is set and self.environmentObject
is set to the correct object.