Create NSIndexSet from integer array in Swift
Asked Answered
H

5

66

I converted an NSIndexSet to an [Int] array using the answer at https://mcmap.net/q/297273/-how-to-get-indexes-from-nsindexset-into-an-nsarray-in-cocoa I need to do essentially the opposite, turning the same kind of array back into an NSIndexSet.

Halfassed answered 22/6, 2016 at 20:12 Comment(0)
C
109

Swift 3

IndexSet can be created directly from an array literal using init(arrayLiteral:), like so:

let indices: IndexSet = [1, 2, 3]

Original answer (Swift 2.2)

Similar to pbasdf's answer, but uses forEach(_:)

let array = [1,2,3,4,5,7,8,10]

let indexSet = NSMutableIndexSet()
array.forEach(indexSet.add) //Swift 3
//Swift 2.2: array.forEach{indexSet.addIndex($0)}

print(indexSet)
Cesta answered 22/6, 2016 at 21:5 Comment(2)
Thanks, but if I use to reloadTableSection is it work to one section?Disforest
@BrunoFernandes Uh... What?Cesta
U
80

This will be a lot easier in Swift 3:

let array = [1,2,3,4,5,7,8,10]
let indexSet = IndexSet(array)

Wow!

Unnecessary answered 22/6, 2016 at 21:8 Comment(3)
Even better, it can be assigned from an Integer Literal. See my answerCesta
@AlexanderMomchliov Excellent, that is even better.Unnecessary
It is very annoying this can't be seen by typing IndexSet.init and using an autocomplete option.Intelligence
D
28

Swift 3+

let fromRange = IndexSet(0...10)
let fromArray = IndexSet([1, 2, 3, 5, 8])

Added this answer because the fromRange option wasn't mentioned yet.

Difficulty answered 7/2, 2017 at 13:58 Comment(0)
I
11

Swift 4.2

From existing array:

let arr = [1, 3, 8]
let indexSet = IndexSet(arr)

From array literal:

let indexSet: IndexSet = [1, 3, 8]
Isocracy answered 17/3, 2019 at 6:26 Comment(0)
G
3

You can use a NSMutableIndexSet and its addIndex method:

let array : [Int] = [1,2,3,4,5,7,8,10]
print(array)
let indexSet = NSMutableIndexSet()
for index in array {
    indexSet.addIndex(index)
}
print(indexSet)
Geophysics answered 22/6, 2016 at 20:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.