7

I have a multiple selection on a UITableview made in Swift and I declare an Array that holds the NSIndexPaths of the selected UITableView Cells.

self.selectedRows = self.preferencesTableView.indexPathsForSelectedRows()

How do I convert this array to readable terms. e.g self.selectedRows is NSlogged like :

Selected Items Strings [ {length = 2, path = 0 - 1}, {length = 2, path = 0 - 0}, {length = 2, path = 0 - 3}]

I wan to be able to convert this to : 1,2,3 .

In Objective C I enumerateObjectsWithOptions through the array and add the id of the array to a mutable array to get what I want.

[self.selectedRows enumerateObjectsWithOptions:NSEnumerationReverse
usingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        NSIndexPath *indexPath = obj;
        [self.selectedCategorieItems addObject:[[[self.categoryArr
objectAtIndex:0] objectForKey:@"id"]objectAtIndex:indexPath.row]];
    }];

How do I do this in Swift?

Moxy
  • 4,162
  • 2
  • 30
  • 49
user3110353
  • 512
  • 2
  • 7
  • 17

2 Answers2

12

You can use map function to return array of indices. It takes closure as argument and iterate over each element of array. $0 is first argument, in our case this is selected index path:

let rows = self.tableView.indexPathsForSelectedRows()?.map{$0.row}

Please note that rows constant will be optional

Sergey Kuryanov
  • 6,114
  • 30
  • 52
2

for swift 2.3

let rows = tableView.indexPathsForSelectedRows.map{$0.map{$0.row}}
mihatel
  • 846
  • 14
  • 34