swift - 如何将 indexPath 数组拆分为单独的 indexPath 数组,每个数组的 indexPath 具有相同的 indexPath.section
问题描述
最近想根据indexPaths删除单元格,所以该函数的输入参数是[IndexPath]
type,我需要将[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]]]
推荐阅读
- logging - 气流/作曲家-信息日志被发送到标准错误?- 导致日志记录显示为错误
- php - 如何在 PHP 脚本执行旁边使用 Caddy 提供静态文件?(交响乐)
- java - 如何将完整的数据库架构公开为 OData 服务
- javascript - 跨 2 个 js 文件保存和读取变量的问题
- scala - 如何使用 Slick 生成条件插入
- javascript - 如何使用一个滑块更改两个输入框
- python - 使用 python 从 sqlite3 获取字段数量
- reactjs - 同一页面上的多个对话框
- pyautogui - pyautogui。不显示位置或 rgb 值
- javascript - 尝试制作会员计数不和谐机器人