Search code examples
swift3iterationcontrol-flow

What is the nil or "empty" countable range in Swift?


In Swift3,

let highestIndex = 7
for index in 1 ..< highestIndex {
    latter(index)
}

however,

let highestIndex = 0, or anything smaller
for index in 1 ..< highestIndex {
    latter(index)
}

that crashes.

So, the ..< operator is impractical in most situations.

So, perhaps, something like this ...

for index in (1 ..< highestIndex).safely() {
    latter(index)
}

How would one write the extension safely ?

Or at worst just a function safely(from,to) which returns a CountableRange, or, an "empty" (?) countable range? (I don't understand if a Swift extension can "catch" an error?)


Solution

  • I am a fan of simple solutions:

    let lowerIndex = 1
    let higherIndex = 0
    for index in lowerIndex ..< max(lowerIndex, higherIndex) {
        latter(index)
    }