在Swift中从整数数组创建NSIndexSet

问题描述 投票:52回答:5

我使用https://stackoverflow.com/a/28964059/6481734的答案将NSIndexSet转换为[Int]数组我需要基本上相反,将相同类型的数组转换回NSIndexSet。

ios swift2 nsarray nsindexset
5个回答
94
投票

Swift 3

可以使用IndexSet直接从数组文字创建init(arrayLiteral:),如下所示:

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

Original answer (Swift 2.2)

pbasdf's answer类似,但使用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)

69
投票

在Swift 3中这将更容易:

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

哇!


25
投票

Swift 3+

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

添加了这个答案,因为还没有提到fromRange选项。


3
投票

你可以使用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)

3
投票

Swift 4.2

从现有阵列:

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

从数组文字:

let indexSet: IndexSet = [1, 3, 8]
© www.soinside.com 2019 - 2024. All rights reserved.