1
votes

I have an empty array:

var indexPathArray: [[NSIndexPath]] = [[]]

And I have a tableView with multiple rows in multiple sections. When a cell is pressed in UITableView, it adds NSIndexPath to the array like following:

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        indexPathArray[indexPath.section].append(indexPath)
    }

If a cell on the first row in section 1 is selected, previous method adds NSIndexPath to the first array in indexPathArray. The result will be like following:

[ [indexPath], [],[] ]

When I deselect the cell, I want to filter out what I selected. I implemented following:

func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) {
    indexPathArray = indexPathArray[indexPath.section].filter({ $0 != indexPath   })
}

In each array in indexPathArray, I'm basically trying to take out if same indexPath item is deselected. For example, if I double tap a cell twice, indexPath item will be added and will be removed by filter function.

However, it throws me an error on filter function saying:

Cannot invoke 'filter' with an argument list of type '(@noescape (NSIndexPath) throws -> Bool)'
expected an argument list of type (@noescape (Self.Generator.Element) throws -> Bool)

What am I doing wrong here?

2
Why don't you use -indexPathsForSelectedRows - Crazyrems

2 Answers

2
votes

The post by Rob does answer your question.

Please also consider that if you just need to keep track of the selected indexes then using a Set is much easier then the array of array of IndexPath you are using.

var set = Set<NSIndexPath>()

Adding an IndexPath

set.insert(indexPath)

Checking if an IndexPath is in the Set

set.contains(indexPath)

Removing an IndexPath

set.remove(indexPath)
1
votes

You are updating indexPathArray with the filtered array of one section. The compiler is confused, because you're updating an [[NSIndexPath]] variable with filter that will result in [NSIndexPath].

Instead of:

indexPathArray = indexPathArray[indexPath.section].filter { $0 != indexPath }

You should instead update that particular section, e.g.:

indexPathArray[indexPath.section] = indexPathArray[indexPath.section].filter { $0 != indexPath }