我使用https://stackoverflow.com/a/28964059/6481734上的答案将 NSIndexSet 转换为 [Int] 数组,我需要做相反的事情,将相同类型的数组转换回 NSIndexSet。
问问题
43883 次
5 回答
107
斯威夫特 3
IndexSet
可以使用 直接从数组文字创建init(arrayLiteral:)
,如下所示:
let indices: IndexSet = [1, 2, 3]
原始答案(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)
于 2016-06-22T21:05:37.880 回答
76
这在 Swift 3 中会容易得多:
let array = [1,2,3,4,5,7,8,10]
let indexSet = IndexSet(array)
哇!
于 2016-06-22T21:08:09.150 回答
27
斯威夫特 3+
let fromRange = IndexSet(0...10)
let fromArray = IndexSet([1, 2, 3, 5, 8])
添加此答案是因为fromRange
尚未提及该选项。
于 2017-02-07T13:58:39.890 回答
11
斯威夫特 4.2
从现有数组:
let arr = [1, 3, 8]
let indexSet = IndexSet(arr)
从数组文字:
let indexSet: IndexSet = [1, 3, 8]
于 2019-03-17T06:26:36.583 回答
3
您可以使用 aNSMutableIndexSet
及其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)
于 2016-06-22T20:48:58.773 回答