【问题标题】:Swift - Get array item with an IndexSetSwift - 使用 IndexSet 获取数组项
【发布时间】:2020-08-04 10:16:29
【问题描述】:

我有我的联系人对象:

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)
        }
    }
}

【问题讨论】:

  • "itemToDelete" 是什么让您认为它只是一项? IndexSet 的全部意义在于它对一组索引进行建模。可以只有一个,也可以是多个。

标签: ios swift swiftui


【解决方案1】:

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

结束

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-10-01
    • 2018-04-05
    • 1970-01-01
    • 1970-01-01
    • 2015-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多