cfisher cfisher - 5 months ago 18
Swift Question

Swift for loop backwards

Is it possible to create an inverted

Range
?

I mean one that goes from 99 to 1, instead of the other way around. My goal is to iterate the values from 99 to 1.

This doesn't compile, but it should give you an idea of what I'm trying to do:

for i in 99...1{
print("\(i) bottles of beer on the wall, \(i) bottles of beer.")
print("Take one down and pass it around, \(i-1) bottles of beer on the wall.")
}


Wha's the easiest way of achieving this in
Swift
?

Answer

You can use stride(through:by:) or stride(to:by:) on anything that conforms to the Strideable protocol. The first one includes the listed value, the second stops one before it.

example:

for i in 99.stride(through: 1, by: -1) { // creates a range of 99...1
  print("\(i) bottles of beer on the wall, \(i) bottles of beer.")
  print("Take one down and pass it around, \(i-1) bottles of beer on the wall.")
}

You can also use reverse():

for i in (1...99).reverse() {
  print("\(i) bottles of beer on the wall, \(i) bottles of beer.")
  print("Take one down and pass it around, \(i-1) bottles of beer on the wall.")
}
Comments