从 Swift 中的整数数组创建 NSIndexSet

Create NSIndexSet from integer array in Swift

我使用 处的答案将 NSIndexSet 转换为 [Int] 数组我需要做相反的事情,将相同类型的数组转换回 NSIndexSet。

您可以使用 NSMutableIndexSet 及其 addIndex 方法:

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)

Swift 3

IndexSet can be created directly from an array literal using init(arrayLiteral:),像这样:

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

原始答案(Swift 2.2)

类似于, 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([=11=])}

print(indexSet)

Swift3:

这会容易得多
let array = [1,2,3,4,5,7,8,10]
let indexSet = IndexSet(array)

哇!

Swift 3+

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

添加此答案是因为尚未提及 fromRange 选项。

Swift 4.2

来自现有数组:

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

来自数组文字:

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