SwiftUI如何按ID而不是索引从ForEach中删除

SwiftUI如何按ID而不是索引从ForEach中删除,swiftui,Swiftui,下面的代码让我感到不舒服 struct HistoryView: View { @ObservedObject var history: History var body: some View { List { ForEach(history.getSessions()) { sess in Text("Duration: \(sess.duration)") }.onDelete

下面的代码让我感到不舒服

struct HistoryView: View {

    @ObservedObject var history: History

    var body: some View {
        List {
            ForEach(history.getSessions()) { sess in
                Text("Duration: \(sess.duration)")
            }.onDelete(perform: self.onDelete)
        }
    }

    private func onDelete(_ indexSet: IndexSet) {
        ...
    }
}

问题是
History
是一个非常异步的东西。这是一个连接到CloudKit的模型。它可能在后台得到更新。理想情况下,如果它更新,这个
视图将立即更新,索引仍然是准确的,但我更希望得到一组要删除的标识符,而不是一组索引。有办法做到这一点吗?注意:这些“历史会话”符合
ForEach
要求的
可识别的
,因此它们都有ID。在我的例子中,它们是
uuid

这可能有助于在删除所选索引时锁定历史记录会话:

struct HistoryView: View {

@ObservedObject var history: History
private let syncQueue = DispatchQueue(label: "com.xxx.yyy.zzz")

var body: some View {
    List {
        ForEach(history.getSessions()) { sess in
            Text("Duration: \(sess.duration)")
        }.onDelete(perform: self.onDelete)
    }
}

private func onDelete(_ indexSet: IndexSet) {
    syncQueue.sync {
        // do the delete
     }
}
}

这可能有助于在删除所选索引时锁定历史记录会话:

struct HistoryView: View {

@ObservedObject var history: History
private let syncQueue = DispatchQueue(label: "com.xxx.yyy.zzz")

var body: some View {
    List {
        ForEach(history.getSessions()) { sess in
            Text("Duration: \(sess.duration)")
        }.onDelete(perform: self.onDelete)
    }
}

private func onDelete(_ indexSet: IndexSet) {
    syncQueue.sync {
        // do the delete
     }
}
}

我认为这不会有帮助,因为要在这里有效地使用锁,需要锁的作用域来包含对history.getSessions()的调用。我认为这不会有帮助,因为要在这里有效地使用锁,需要锁的作用域来包含对history.getSessions()的调用。