Skip to content

Instantly share code, notes, and snippets.

@malhal
Created October 26, 2024 18:42
Show Gist options
  • Save malhal/81488068526144b02a177c0e3523ec12 to your computer and use it in GitHub Desktop.
Save malhal/81488068526144b02a177c0e3523ec12 to your computer and use it in GitHub Desktop.
Cached sort
import SwiftUI
struct Counter: Identifiable, Equatable {
let id = UUID()
var count = 0
}
struct ContentView: View {
@State var counters: [Counter] = [.init(), .init(), .init()]
var body: some View {
NavigationStack {
HStack {
SortedView(counters: $counters)
SortedView(counters: $counters)
}
}
}
}
struct SortedView: View {
@Binding var counters: [Counter]
@State var sortedCounters: [Binding<Counter>] = []
@State var ascending = false
var body: some View {
List {
Button(ascending ? "Ascending" : "Descending") {
ascending.toggle()
}
ForEach(sortedCounters) { $c in
Button("\(c.count, format: .number)") {
c.count += 1
}
}
}
.onChange(of: counters, initial: true) {
withAnimation {
sortedCounters = $counters.map(\.projectedValue)
sort()
}
}
.onChange(of: ascending) {
withAnimation {
sort()
}
}
}
func sort() {
let sort = SortDescriptor(\Binding<Counter>.wrappedValue.count, order: ascending ? .forward : .reverse)
sortedCounters.sort(using: sort)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment