Swift: Convert IndexSet to [IndexPath]

Viewed 1976

I want to get [IndexPath] from IndexSet in Swift 5. There is a question to convert NSIndexSet to Array<NSIndexPath *> in Objective-C. But there is no method enumerateIndexesUsingBlock in Swift 5. Who knows the way?

2 Answers

Use map on indexes to create custom IndexPath like this:

let customIndexPaths = indexes.map { IndexPath(row: $0, section: 0) }
// Or, You can use the short-form, credits: @Vadian
let customIndexPaths: [IndexPath] = indexes.map { [$0, 0] }

There is also an initializer for IndexPath that you can use:

let indexes: IndexSet = [0, 1]
let indexPath = IndexPath(indexes: indexes) // Note: this initializer returns just one indexPath not an array `[IndexPath]`

You can use extension.

extension IndexSet {
    func indexPaths(_ section: Int) -> [IndexPath] {
        return self.map{IndexPath(item: $0, section: section)}
    }
}
Related