brandonscript
brandonscript

Reputation: 72885

Get [NSIndexPath] array for rows in section of UITableView in Swift

I've got a section of rows in a tableView (section 1) and I need to initialize an [NSIndexPath] array for all rows in that section.

I know I can count the number of rows in the section easily enough:

let rowsInSection = tableView.numberOfRowsInSection(1)

But that only gets me the row count, not the index paths.

What's the cleanest, most "Swift-like" way of retrieving the index paths?

An example of what I'm looking for:

func indexPathsForRowsInSection(section: Int) -> [NSIndexPath] {
    // magic happens here
    return indexPathsForRowsInSection
}

Upvotes: 1

Views: 4319

Answers (4)

Pavan Sisode
Pavan Sisode

Reputation: 61

 let section = 1
 let numberOfRows = 15

 let indexPaths = (0..<numberOfRows).map { i in return 
                                          IndexPath(item:i, section: section)  
                                         }

Upvotes: 0

brandonscript
brandonscript

Reputation: 72885

Here's a concise Swift 3 extension for UITableView based on Vincent and Matt's answers:

extension UITableView {
    func indexPathsForRowsInSection(_ section: Int) -> [NSIndexPath] {
        return (0..<self.numberOfRows(inSection: section)).map { NSIndexPath(row: $0, section: section) }
    }
}

// usage
tableView.indexPathsForRowsInSection(aNumber)

Upvotes: 0

matt
matt

Reputation: 535140

Like this in Swift 3:

func indexPathsForRowsInSection(_ section: Int, numberOfRows: Int) -> [NSIndexPath] {
    return (0..<numberOfRows).map{NSIndexPath(row: $0, section: section)}
}

Upvotes: 11

Vincent Bernier
Vincent Bernier

Reputation: 8664

I don't know why you want this, but you could do as follow:

let paths = (0..<tableView.numberOfRowsInSection(section)).map { NSIndexPath(forRow: $0, inSection: section) }
return paths

Upvotes: 4

Related Questions