2016-06-22 26 views

risposta

74

Swift 3

IndexSet possono essere creati direttamente da un array letterale utilizzando init(arrayLiteral:), in questo modo:

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

originale risposta (Swift 2.2)

Simile a pbasdf's answer, ma usa 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) 
+0

Grazie, ma se utilizzo la funzione reloadTableSection, funziona su una sezione? – Bruno

+1

@BrunoFernandes Uh ... Cosa? – Alexander

2

è possibile utilizzare un NSMutableIndexSet e il suo addIndex metodo:

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

Questo sarà molto più facile a Swift 3:

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

Wow!

+0

Sembra buono, non vedo l'ora! – Alexander

+0

Ancora meglio, può essere assegnato da un numero intero letterale. Vedi la mia risposta – Alexander

+0

@AlexanderMomchliov Eccellente, questo è meglio ancora. – matt

-1

Informazioni sull'uso Set<Int> dal IndexSet è in sola lettura (non è possibile aggiungere nuovi articoli)?

var set: Set<Int> = [0] 
set.insert(1) 
set.insert(2) 
return set 
+0

IndexSet - non è di sola lettura (immutabile), dipende dalla dichiarazione come let o var. Non confondere con NSIndexSet. – vsilux

11

Swift 3

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

Aggiunto questa risposta perché l'opzione fromRange non era ancora menzionato.

Problemi correlati