I have a list, and I want to use swipeAction to either set or unset a property on the list items. My problem is that the function to decide if the property is set or unset is slow, and it runs not just when the user swipes (as I thought) but for every item as the list loads. Here is a mockup of the problem.
Note: In real life, the hasStar() function only takes 50ms, but the list is thousands of elements long, so the result is the same, a slow-loading list.
Is there a better way to do this?
struct ContentView: View {
let data = (1...10).map { "Item \($0)" }
var body: some View {
VStack {
List() {
ForEach(data, id: \.self) { item in
Text(item)
.swipeActions(edge: .leading) {
if hasStar() {
Button {
print("star removed")
} label: {
Label("Remove star", systemImage: "star.slash").font(.title)
}.tint(.red)
} else {
Button {
print("star added")
} label: {
Label("Add star", systemImage: "star").font(.title)
}.tint(.green)
}
}
}
}
}
}
func hasStar() -> Bool {
print("Slow function started")
sleep(1)
print("Slow function finished")
return true
}
}