Skip to content

Instantly share code, notes, and snippets.

@zakbarlow1995
Created April 27, 2020 09:36
Show Gist options
  • Save zakbarlow1995/714cf735a96245532c577fb35841c723 to your computer and use it in GitHub Desktop.
Save zakbarlow1995/714cf735a96245532c577fb35841c723 to your computer and use it in GitHub Desktop.
Swift - Get IndexPath array between startIndex & endIndex helper function
func getIndexPathArrayBetween(_ startIndex: Int, and endIndex: Int, section: Int = 0) -> [IndexPath] {
assert(startIndex >= 0 && endIndex > startIndex, "startIndex >= 0 && endIndex > startIndex")
return (startIndex...endIndex).map { IndexPath(row: $0, section: section) }
}
@zakbarlow1995
Copy link
Author

zakbarlow1995 commented Apr 27, 2020

Example use-case: API pagination request result (apiResult) returning array of TableViewDataSource (items)

let startIndex = dataSourceObjects.count                 // Start index of new datasource addtions
dataSourceObjects.append(contentsOf: apiResult.items)    // Add the new items to dataSourceObjects array
let endIndex = dataSourceObjects.count - 1               // End index after new data addition = count -1

tableView.beginUpdates()
tableView.insertRows(at: getIndexPathArrayBetween(startIndex, and: endIndex), with: .none)
tableView.endUpdates()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment