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

标签 swift indexpath

最近想根据indexPaths删除单元格,所以函数的入参是[IndexPath]类型,需要根据把[IndexPath]拆分成几个数组indexPath.section,有什么简单的方法吗? 例如

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]

最佳答案

一个可能的解决方案是首先构建一个字典,其中键是节号,值是该节中 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]]]

关于swift - 如何将 indexPath 数组拆分为单独的 indexPath 数组,每个数组的 indexPath 具有相同的 indexPath.section,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55877235/

相关文章:

ios - 如何使用 youtube-ios-player-helper 库在 iOS 中更改 youtube 视频的音量

xcode - 仅使用 CPU 的操作

ios - (Swift) fatal error : Index out of range

ios - 如何在 Collection View 中显示广告

ios - 我想制作带有动态行的动态部分的 Uitableview

swift - 代码转换 swift 2 --> 3 导致索引路径处的二进制运算符错误

ios - 编码和解码函数如何使用 NSCoding 在 Swift 3 中工作?

swift - 为什么我的 SKSpriteNode 可以工作,但只是暂时的

swift - 如何处理主队列上的多个 moc