Elegant Swift way to handle negative index in for

2019-09-11 08:00发布

I'm new to Swift and trying to find an elegant way to handle a for loop variable that can be negative.

func funForLoops(_ loop:Int) {
    for i in 0..<loop {
        print("Hello \(i)")
    }
}
funForLoops(1) // prints Hello 0
funForLoops(0) // doesn't execute
funForLoops(-1) // runtime error "fatal error: Can't form Range with  upperBound < lowerBound"

Is there a simpler way to check this than this:

if (loop >= 0) {
    for i in 0..<loop {
        print("Hello \(i)")
    }
}

Or this:

for i in 0..<(loop >= 0 ? loop : 0) {

2条回答
神经病院院长
2楼-- · 2019-09-11 08:18

On the assumption you mean "if it's negative, do nothing," (which is not obvious; you might mean "decrement," which is why it would be ambiguous if it weren't an exception) the syntax you want is:

for i in 0..<max(0, loop) { }

This is a fine syntax when it is necessary, but in most cases if the value can be surprisingly negative, you have a deeper problem in the structure of the program and should have resolved the issue sooner.

查看更多
Viruses.
3楼-- · 2019-09-11 08:19

Yeah, its not obvious what result you want to have. If you just need to iterate, no matter negative or not

func forLoop(count: Int) {
  for i in min(count, 0)..<max(0, count) {
    print(i)
  }
}

Or less code

func forLoop(count: Int) {
  for i in 0..<abs(count) {
    print(i)
  }
}

The only difference here is that first example will produce output with negative values and stops before 0.

Second example will start from 0 and finish with count-1

查看更多
登录 后发表回答