3

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?

cfischer
  • 24,452
  • 37
  • 131
  • 214
  • See http://stackoverflow.com/questions/24508592/how-to-iterate-for-loop-in-reverse-order-in-swift the by allows you to control the step of the range – Scriptable Jun 07 '16 at 22:46

1 Answers1

10

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 reversed():

for i in (1...99).reversed() {
  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.")
}
Deyton
  • 2,364
  • 1
  • 15
  • 10