Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create NSIndexSet from integer array in Swift

I converted an NSIndexSet to an [Int] array using the answer at https://stackoverflow.com/a/28964059/6481734 I need to do essentially the opposite, turning the same kind of array back into an NSIndexSet.

like image 529
Jacolack Avatar asked Jun 22 '16 20:06

Jacolack


3 Answers

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)
like image 156
Alexander Avatar answered Oct 23 '22 15:10

Alexander


This will be a lot easier in Swift 3:

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

Wow!

like image 77
matt Avatar answered Oct 23 '22 16:10

matt


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.

like image 28
Arnaud Avatar answered Oct 23 '22 16:10

Arnaud