问题描述
我有我的联系人对象:
struct Contact: Codable, Identifiable {
var id: Int = 0
var name: String
var lastName: String
var phoneNumber: String
}
在我看来,我有一个将从服务器获取的联系人列表.
And in my view I have a list of contacts that will be fetched from a server.
List {
ForEach(viewModel.contacts) { contact in
ContactView(contact: contact)
}
.onDelete(perform: self.viewModel.delete)
}
当我删除联系人时,我调用viewModel方法delete wich,仅从数组中删除该项目.但是由于我将向服务器发出删除联系人的请求,因此我想获取有关我要删除的项目(例如ID)的信息.
When I delete a contact I call my viewModel method delete wich only removes the item from the array. But since I will make a server request to delete a contact, I would like to get info about the item I'm deleting, like the 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)
}
}
我想知道我是否可以做这样的事情:
I wonder if I can do something like this:
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
在语义上是异步的,通常,在一个用户操作中可能会删除多个联系人,我会像下面这样
Taking into account that mentioned deleteRequest
semantically is asynchronous and there might be, in general, several contacts deleted in one user action, I would do it like below
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
这篇关于Swift-使用IndexSet获取数组项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!