1

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
}
2
  • Use a for loop to populate the array. Commented Mar 4, 2016 at 3:40
  • you can use for to loop the count of row, then declare indexPath directly like let index = NSIndexPath(forItem: i, inSection: 0). i will be your item row Commented Mar 4, 2016 at 3:43

4 Answers 4

11

Like this in Swift 3:

func indexPathsForRowsInSection(_ section: Int, numberOfRows: Int) -> [NSIndexPath] {
    return (0..<numberOfRows).map{NSIndexPath(row: $0, section: section)}
}
Sign up to request clarification or add additional context in comments.

4 Comments

Great, nice solution!
Updated for Swift 3
@brandonscript Note my modification of your update: I'd remove the section label from the first parameter so as not have to call this by saying ...Section(section....
Ah yes absolutely.
4

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

Comments

0

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)

Comments

0
 let section = 1
 let numberOfRows = 15

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.