Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift - How to get number values for selected rows in UITableview

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?

like image 494
user3110353 Avatar asked May 04 '15 08:05

user3110353


2 Answers

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

like image 72
Sergey Kuryanov Avatar answered Oct 01 '22 01:10

Sergey Kuryanov


for swift 2.3

let rows = tableView.indexPathsForSelectedRows.map{$0.map{$0.row}}
like image 23
mihatel Avatar answered Sep 30 '22 23:09

mihatel