Create NSIndexSet from integer array in Swift

独自空忆成欢 提交于 2019-12-06 16:29:34

问题


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.


回答1:


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)



回答2:


This will be a lot easier in Swift 3:

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

Wow!




回答3:


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.




回答4:


Swift 4.2

From existing array:

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

From array literal:

let indexSet: IndexSet = [1, 3, 8]



回答5:


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)


来源:https://stackoverflow.com/questions/37977404/create-nsindexset-from-integer-array-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!