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?
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.")
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With