问题
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