Search code examples
swiftindexpath

How to split indexPath array into seperate array of indexPath, each array's indexPath has same indexPath.section


Recently I want to delete cells according to indexPaths, so the input parameter of the function is [IndexPath] type, I need to split the [IndexPath] to several arrays according to the indexPath.section, is there any easy way to do this? For example

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

want to convert this to

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]

Solution

  • One possible solution is to first build a dictonary where the keys are the section numbers and the values are the array of IndexPath in that section.

    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
    }
    

    Then you can map this dictionary into an array of the path arrays. But first sort those arrays by the 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)
    

    Output:

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