ios - Swift - 使用 IndexSet 获取数组项
问题描述
我有我的联系人对象:
struct Contact: Codable, Identifiable {
var id: Int = 0
var name: String
var lastName: String
var phoneNumber: String
}
在我看来,我有一个将从服务器获取的联系人列表。
List {
ForEach(viewModel.contacts) { contact in
ContactView(contact: contact)
}
.onDelete(perform: self.viewModel.delete)
}
当我删除一个联系人时,我调用我的 viewModel 方法 delete,它只从数组中删除该项目。但由于我将发出服务器请求以删除联系人,因此我想获取有关我正在删除的项目的信息,例如 ID。
class ContactsViewModel: ObservableObject {
@Published contacts = [
Contact(id: 1, name: "Name 1", lastName: "Last Name 1", phoneNumber: "613456789"),
Contact(id: 2, name: "Name 2", lastName: "Last Name 2", phoneNumber: "623456789"),
Contact(id: 3, name: "Name 3", lastName: "Last Name 3", phoneNumber: "633456789"),
Contact(id: 4, name: "Name 4", lastName: "Last Name 4", phoneNumber: "643456789")
]
func delete(at offsets: IndexSet) {
self.contacts.remove(atOffsets: offsets)
}
}
我想知道我是否可以做这样的事情:
func delete(at offsets: IndexSet) {
// Get the contact from array using the IndexSet
let itemToDelete = self.contacts.get(at: offsets)
deleteRequest(itemToDelete.id){ success in
if success {
self.contacts.remove(atOffsets: offsets)
}
}
}
解决方案
考虑到deleteRequest
语义上提到的是异步的,并且通常可能在一个用户操作中删除了多个联系人,我会这样做如下
func delete(at offsets: IndexSet) {
// preserve all ids to be deleted to avoid indices confusing
let idsToDelete = offsets.map { self.contacts[$0].id }
// schedule remote delete for selected ids
_ = idsToDelete.compactMap { [weak self] id in
self?.deleteRequest(id){ success in
if success {
DispatchQueue.main.async {
// update on main queue
self?.contacts.removeAll { $0.id == id }
}
}
}
}
}
注意:还需要 UI 中的一些反馈来标记已进行的联系人并禁止用户对其进行其他操作,直到相应结束deleteRequest
推荐阅读
- php - 如果特定记录不存在,如何仅选择数据
- python - 当一个参数是`find "path/" -type f -name "*.xml"`时如何传递两个参数?
- python - 如何根据 Python 中的特定条件在更大的列表中分解列表?
- spring - StreamBridge Final 无法模拟
- python - Spotify API OAuth:如何退出用户登录的命令提示符
- lua - 为什么不能以表作为其键之一来初始化 Lua 表?
- reactjs - ModuleNotFoundError:找不到模块:错误:无法解析“./Select-d680feef.esm.js”
- amazon-web-services - 如何查找适用于 AMI 的实例类型列表
- compiler-errors - 目标“CMakeFiles/check_lab0”的配方在斯坦福 CS144 自学中失败
- python - 如何使用python opencv处理海康威视解码回调函数