'looping thru IndexSet

The following quite simple for loop thru NSIndexSet must be ported to Swift

NSIndexSet indexSet = self.selectedRowIndexes;
for (NSUInteger index = indexSet.firstIndex; index != NSNotFound; index = [indexSet indexGreaterThanIndex:index]) {
    // do something with use of index
}

but i can not express same with a Swift IndexSet in a for loop as Swift does not allow C-style notations.

So how do does a ported version with same results from code above look like in Swift?



Solution 1:[1]

to wrap up what i learned..

var indexSet : IndexSet = IndexSet.init()

indexSet.insert(10)
indexSet.insert(12)
indexSet.insert(2)
indexSet.insert(64)

for n in indexSet {
    print("for n in indexSet -> \(n)")
}

for n in indexSet.enumerated() {
    print("for n in indexSet.enumerated() -> \(n)")
}

for n in indexSet.indices {
    print("for n in indexSet.indices -> \(n)")
}

results in

for n in indexSet -> 2
for n in indexSet -> 10
for n in indexSet -> 12
for n in indexSet -> 64
for n in indexSet.enumerated() -> (offset: 0, element: 2)
for n in indexSet.enumerated() -> (offset: 1, element: 10)
for n in indexSet.enumerated() -> (offset: 2, element: 12)
for n in indexSet.enumerated() -> (offset: 3, element: 64)
for n in indexSet.indices -> index 2 in a range of 2..<3 [range #1/4]
for n in indexSet.indices -> index 10 in a range of 10..<11 [range #2/4]
for n in indexSet.indices -> index 12 in a range of 12..<13 [range #3/4]
for n in indexSet.indices -> index 64 in a range of 64..<65 [range #4/4]

meaning, it is so simple, it is almost embarrassing

for n in indexSet {
    print("for n in indexSet -> \(n)")
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ol Sen