首页 > 解决方案 > 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)
        }
    }
}

标签: iosswiftswiftui

解决方案


考虑到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


推荐阅读