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