Swift 如何将indexPath数组拆分为独立的indexPath数组,每个数组';s indexPath具有相同的indexPath.section

Swift 如何将indexPath数组拆分为独立的indexPath数组,每个数组';s indexPath具有相同的indexPath.section,swift,indexpath,Swift,Indexpath,最近我想根据IndexPath删除单元格,所以函数的输入参数是[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)] 要将此转

最近我想根据IndexPath删除单元格,所以函数的输入参数是
[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]

一种可能的解决方案是首先构建一个dictional,其中键是节号,值是该节中
indepath
的数组

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)
let sectionPaths=pathDict.sorted{(arg0,arg1)->Bool-in
返回arg0.key
输出:

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

  • 我们需要一个HashMap,映射到密钥上
  • 我们需要把字典分类
  • 我们需要提取字典的值并将它们附加到数组中
  • 我们需要返回那个数组
var IndexPath=[IndexPath(行:0,节:1),
IndexPath(行:1,节:1),
IndexPath(第2行,第1节),
IndexPath(行:2,节:0)
]
扩展数组,其中元素==IndexPath{
func splitArray()->Array{
var tempDict=[String:[IndexPath]]()
自我元素{
设section=element.section
如果tempDict[String(section)]!=nil{
//某些元素附加
如果var array=tempDict[String(section)]{
array.append(元素)
tempDict[String(section)]=数组
}
}否则{
tempDict[String(section)]=[element]
}
}
//字典可能没有排序,请对字典排序
tempDict.sorted{$0.key>$1.key}
var returnedArray=Array()
用于tempDict中的(键、值){
returnedArray.append(值)
}
返回阵列
}
}
打印(indexpath.splitArray())
使用过滤器:

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

这是不可伸缩的。如果原始的
indexPaths
有几十个节怎么办?您不需要为每个部分创建单独变量的解决方案。如果没有呢?这只是对这个问题的快速回答,当然它不是最有效和可扩展的。感谢您提到这一点。请不要忘记通过单击答案左侧最能解决您问题的复选标记来表明您的问题已成功回答。你在这里这么多年来都没有问过任何问题。你应该回顾你所有的问题,在适当的情况下,检查答案是否能最好地解决这个问题。
let indexPath0 = indexPaths.filter { $0.section == 0 }
let indexPath1 = indexPaths.filter { $0.section == 1 }