【发布时间】:2016-10-24 22:46:08
【问题描述】:
我使用https://stackoverflow.com/a/28964059/6481734 的答案将 NSIndexSet 转换为 [Int] 数组,我需要做相反的事情,将相同类型的数组转换回 NSIndexSet。
【问题讨论】:
标签: ios swift2 nsarray nsindexset
我使用https://stackoverflow.com/a/28964059/6481734 的答案将 NSIndexSet 转换为 [Int] 数组,我需要做相反的事情,将相同类型的数组转换回 NSIndexSet。
【问题讨论】:
标签: ios swift2 nsarray 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)
【讨论】:
IndexSet 可以使用init(arrayLiteral:) 直接从数组字面量创建,如下所示:
let indices: IndexSet = [1, 2, 3]
类似于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)
【讨论】:
这在 Swift 3 中会容易得多:
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 选项。
【讨论】:
斯威夫特 4.2
从现有数组:
let arr = [1, 3, 8]
let indexSet = IndexSet(arr)
来自数组字面量:
let indexSet: IndexSet = [1, 3, 8]
【讨论】: