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?
Asked
Active
Viewed 2,462 times
2

Dávid Pásztor
- 51,403
- 9
- 85
- 116

Emre Kayaoglu
- 561
- 2
- 5
- 19
-
Is this what you are looking for https://stackoverflow.com/a/39639273/1187415 ? – Martin R Jun 11 '20 at 16:31
-
Can I get full IndexPath array from IndexSet? – Emre Kayaoglu Jun 11 '20 at 16:36
2 Answers
3
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]`

Frankenstein
- 15,732
- 4
- 22
- 47
-
1
-
Your last option `indexes.map { [$0, 0] }` doesn't make any sense. It results in a 2d array of integers. Btw you can simply use `indexes.map(IndexPath.init)` – Leo Dabus Jun 12 '20 at 03:51
-
@LeoDabus I forgot to mention that you have to annotate the type in this case: `let customIndexPaths : [IndexPath] = indexes.map { [$0, 0] }` – vadian Jun 12 '20 at 07:55
1
You can use extension.
extension IndexSet {
func indexPaths(_ section: Int) -> [IndexPath] {
return self.map{IndexPath(item: $0, section: section)}
}
}

ariane26
- 163
- 1
- 6
- 25