Nice programing

Swift의 정수 배열에서 NSIndexSet 만들기

nicepro 2020. 12. 31. 23:29
반응형

Swift의 정수 배열에서 NSIndexSet 만들기


https://stackoverflow.com/a/28964059/6481734 의 답변을 사용하여 NSIndexSet을 [Int] 배열로 변환했습니다. 본질적으로 반대의 작업을 수행하여 동일한 종류의 배열을 다시 NSIndexSet으로 전환해야합니다.


스위프트 3

IndexSet다음 init(arrayLiteral:)과 같이를 사용하여 배열 리터럴에서 직접 만들 수 있습니다 .

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

원래 답변 (Swift 2.2)

유사 pbasdf의 대답 만 사용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]

a 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)

참조 URL : https://stackoverflow.com/questions/37977404/create-nsindexset-from-integer-array-in-swift

반응형