如何将indexPath数组拆分为单独的indexPath数组,每个数组的indexPath具有相同的indexPath.section

时间:2019-04-27 04:26:36

标签: swift

最近我想根据indexPaths删除单元格,因此该函数的输入参数为[IndexPath]类型,我需要根据indexPath.section将[IndexPath]拆分为多个数组,是否存在任何简单的方法来做到这一点? 例如

indexPaths = 
[IndexPath(row: 0, section: 1),
 IndexPath(row: 1, section: 1), 
 IndexPath(row: 2, section: 1), 
 IndexPath(row: 2, section: 0)]

想要将其转换为

indexPath1 = 
[IndexPath(row: 0, section: 1),
 IndexPath(row: 1, section: 1), 
 IndexPath(row: 2, section: 1)]

indexPath0 = 
[IndexPath(row: 2, section: 0)]

// maybe get a [Array]
[indexPath0, indexPath1]

3 个答案:

答案 0 :(得分:2)

一个可能的解决方案是首先构建字典,其中键是节号,值是该节中IndexPath的数组。

let indexPaths = [
    IndexPath(row: 0, section: 1),
    IndexPath(row: 1, section: 1),
    IndexPath(row: 2, section: 1),
    IndexPath(row: 2, section: 0),
]

let pathDict = Dictionary(grouping: indexPaths) { (path) in
    return path.section
}

然后,您可以将此字典映射到路径数组的数组中。但是首先请按部分对这些数组进行排序。

let sectionPaths = pathDict.sorted { (arg0, arg1) -> Bool in
    return arg0.key < arg1.key // sort by section
}.map { $0.value } // get just the arrays of IndexPath

print(sectionPaths)

输出:

  

[[[[0,2]],[[1,0],[1,1],[1,2]]]

答案 1 :(得分:0)

  • 我们需要一个HashMap,映射到密钥上。
  • 我们需要对字典进行排序
  • 我们需要提取字典值并将其附加到数组
  • 我们需要返回该数组
    Geocoder.init("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");

    Geocoder.from(41.89, 12.49)
        .then(json => {
            var addressComponent = json.results[0].formatted_address;
      console.log(addressComponent);
      console.log(addressComponent)
     alert(addressComponent);
        })
      .catch(error => console.warn(error));
    }

答案 2 :(得分:0)

使用过滤器:

let indexPath0 = indexPaths.filter { $0.section == 0 }
let indexPath1 = indexPaths.filter { $0.section == 1 }