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) {
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:
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.
Yeah, its not obvious what result you want to have. If you just need to iterate, no matter negative or not
Or less code
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