Swift 快速倒转

Swift 快速倒转,swift,for-loop,iteration,Swift,For Loop,Iteration,是否可以创建反转的范围 我的意思是从99到1,而不是相反。我的目标是迭代从99到1的值 这不会编译,但它会让您了解我要做的事情: 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.") } 在Swift中实现这一点最

是否可以创建反转的
范围

我的意思是从99到1,而不是相反。我的目标是迭代从99到1的值

这不会编译,但它会让您了解我要做的事情:

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.")
}
Swift
中实现这一点最简单的方法是什么?

您可以在任何符合
可跨越的
协议的东西上使用
跨步(通过:通过:)
跨步(通过:通过:)
。第一个包含列出的值,第二个在它之前停止

例如:

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.")
}
您还可以使用
反向()

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.")
}
请参阅允许您控制范围步长的by