Created
October 26, 2024 18:42
-
-
Save malhal/81488068526144b02a177c0e3523ec12 to your computer and use it in GitHub Desktop.
Cached sort
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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