Elegant Swift way to handle negative index in for loop

孤街醉人 提交于 2019-12-12 03:43:27

问题


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

回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/39652075/elegant-swift-way-to-handle-negative-index-in-for-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!