ios 在 Swift 中从整数数组创建 NSIndexSet
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37977404/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Create NSIndexSet from integer array in Swift
提问by Jacolack
I converted an NSIndexSet to an [Int] array using the answer at https://stackoverflow.com/a/28964059/6481734I need to do essentially the opposite, turning the same kind of array back into an NSIndexSet.
我使用https://stackoverflow.com/a/28964059/6481734 上的答案将 NSIndexSet 转换为 [Int] 数组我需要基本上做相反的事情,将相同类型的数组转换回 NSIndexSet。
回答by Alexander - Reinstate Monica
Swift 3
斯威夫特 3
IndexSet
can be created directly from an array literal using init(arrayLiteral:)
, like so:
IndexSet
可以使用 直接从数组文字创建init(arrayLiteral:)
,如下所示:
let indices: IndexSet = [1, 2, 3]
Original answer (Swift 2.2)
原始答案(Swift 2.2)
Similar to pbasdf's answer, but uses forEach(_:)
类似于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(let array = [1,2,3,4,5,7,8,10]
let indexSet = IndexSet(array)
)}
print(indexSet)
回答by matt
This will be a lot easier in Swift 3:
这在 Swift 3 中会容易很多:
let fromRange = IndexSet(0...10)
let fromArray = IndexSet([1, 2, 3, 5, 8])
Wow!
哇!
回答by Nycen
Swift 3+
斯威夫特 3+
let arr = [1, 3, 8]
let indexSet = IndexSet(arr)
Added this answer because the fromRange
option wasn't mentioned yet.
添加此答案是因为fromRange
尚未提及该选项。
回答by jposadas
Swift 4.2
斯威夫特 4.2
From existing array:
从现有数组:
let indexSet: IndexSet = [1, 3, 8]
From array literal:
从数组文字:
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)
回答by pbasdf
You can use a NSMutableIndexSet
and its addIndex
method:
您可以使用 aNSMutableIndexSet
及其addIndex
方法: