首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何将indexPath数组拆分为独立的indexPath数组,每个数组的indexPath具有相同的indexPath.section

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

Stack Overflow用户
提问于 2019-04-27 04:26:35
回答 3查看 232关注 0票数 1

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

代码语言:javascript
复制
indexPaths = 
[IndexPath(row: 0, section: 1),
 IndexPath(row: 1, section: 1), 
 IndexPath(row: 2, section: 1), 
 IndexPath(row: 2, section: 0)]

要将此转换为

代码语言:javascript
复制
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]
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2019-04-27 04:45:31

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

代码语言:javascript
复制
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
}

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

代码语言:javascript
复制
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]]

票数 3
EN

Stack Overflow用户

发布于 2019-04-27 04:57:41

  • 我们需要一个HashMap,映射到密钥上。
  • 我们需要整理字典
  • 我们需要提取字典的值并将它们附加到数组中。
  • 我们需要返回那个数组
代码语言:javascript
复制
var indexPaths = [IndexPath(row: 0, section: 1),
     IndexPath(row: 1, section: 1),
     IndexPath(row: 2, section: 1),
     IndexPath(row: 2, section: 0)
]

extension Array where Element == IndexPath {
    func splitArray() ->  Array<[IndexPath]> {
        var tempDict = [String : [IndexPath]]()
        for element in self {
            let section = element.section
            if tempDict[String(section)] != nil {
                // some element append
                if var array = tempDict[String(section)] {
                    array.append(element)
                    tempDict[String(section)] = array
                }

            } else {
                tempDict[String(section)] = [element]
            }
        }

        // dictionary mayn't have sorted, sort the dictionary 

        tempDict.sorted{ $0.key > $1.key }

        var returnedArray = Array<[IndexPath]>()
        for (key, value) in tempDict {
           returnedArray.append(value)
        }

        return returnedArray
    }
}

print(indexPaths.splitArray())
票数 0
EN

Stack Overflow用户

发布于 2019-04-27 05:42:13

使用过滤器:

代码语言:javascript
复制
let indexPath0 = indexPaths.filter { $0.section == 0 }
let indexPath1 = indexPaths.filter { $0.section == 1 }
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55877235

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档