【问题标题】:Remove each individual item from an array one by one after they are used?使用后将每个单独的项目从数组中逐一删除?
【发布时间】:2020-05-20 22:43:11
【问题描述】:

我有一张地图,在我从数组中添加一个组件后,我希望从该数组中删除该特定组件。我尝试了过滤然后删除的方法,但它只从数组中删除了一项。我需要在使用后删除数组的每个项目。这是它的样子:

   private var labelViews: [MapLabelView] = []


    private func removeAllLabels() {
        guard let mapController = viewModel.mapController,
            let currentMap = mapController.currentMap else {
                return
        }
    >         labelViews.forEach { view in
    >             DispatchQueue.main.async {
    >                 mapController.removeComponent(view, on: currentMap)
    >                 self.labelViews.removeAll(where: {$0 == view})                
                  if let index = self.campusLabelViews.firstIndex(of: view) 
                  {self.campusLabelViews.remove(at: index)}//This is what I tried doing, but its only removing the first view and not ones after that.
}

【问题讨论】:

  • 你能举个例子,你的数组在手术前后是什么样子的吗?
  • @koen 它是一组自定义对象,我正在检查删除后的计数,但是当它应该为空时,它只显示了一个更少的对象
  • 你能写出来吗?例如之前:["one", "two", "three"],之后:["two", three"]。或者类似的东西?
  • @koen 有点难,因为它们是视图,但我正在使用的功能在上面发布
  • 你需要获取所有索引 .. 而不是第一个正确的?

标签: ios arrays swift filter


【解决方案1】:

这里是扩展,您可以通过它获取数组中存在的某个视图的所有索引

extension Array where Element: Equatable {
    func allIndexes(of element: Element) -> [Int] {
        return self.enumerated().filter({ element == $0.element }).map({ $0.offset })
    }
}

所以你的代码会变成

let indexs = self.campusLabelViews. allIndexes(of: view) // it return all indexes of that particular view 
for index in indexs {
    self.campusLabelViews.remove(at: index)
  }

【讨论】:

    猜你喜欢
    • 2019-05-17
    • 2013-06-04
    • 2021-01-28
    • 1970-01-01
    • 1970-01-01
    • 2015-08-20
    • 2023-03-29
    • 2021-07-23
    • 2020-08-09
    相关资源
    最近更新 更多