Skip to content

Instantly share code, notes, and snippets.

@malhal
Created October 27, 2024 12:01
Show Gist options
  • Save malhal/4090adc4c8ae8529583e0d600926c74f to your computer and use it in GitHub Desktop.
Save malhal/4090adc4c8ae8529583e0d600926c74f to your computer and use it in GitHub Desktop.
cached sort 2
import SwiftUI
struct Counter: Identifiable, Equatable {
let id = UUID()
var count = 0
}
struct SortedCounters {
var _counters: [Binding<Counter>] = []
var counters: [Binding<Counter>] {
get {
_counters
}
set {
_counters = newValue
sort()
}
}
var ascending = false {
didSet {
sort()
}
}
mutating func sort() {
let sort = SortDescriptor(\Binding<Counter>.wrappedValue.count, order: ascending ? .forward : .reverse)
_counters.sort(using: sort)
}
}
struct ContentView2: View {
@State var counters: [Counter] = [.init(), .init(), .init()]
@State var sortedCounters1 = SortedCounters()
@State var sortedCounters2 = SortedCounters()
@State var callBody = 0
var body: some View {
NavigationStack {
Button("callBody \(callBody)") {
callBody += 1
}
HStack {
CounterView(x: callBody, sortedCounters: $sortedCounters1)
CounterView(x: callBody, sortedCounters: $sortedCounters2)
}
}
.onChange(of: counters, initial: true) {
let x = $counters.map(\.projectedValue)
sortedCounters1.counters = x
sortedCounters2.counters = x
}
}
}
struct CounterView: View {
let x: Int
@Binding var sortedCounters: SortedCounters
var body: some View {
let _ = print(Self._printChanges())
List {
Button(sortedCounters.ascending ? "Ascending" : "Descending") {
withAnimation {
sortedCounters.ascending.toggle()
}
}
ForEach(sortedCounters.counters) { $c in
Button("\(c.count, format: .number)") {
withAnimation {
c.count += 1
}
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment