Swift for loop向后

时间:2016-06-07 22:45:44

标签: swift for-loop iteration

是否可以创建倒置Range

我的意思是从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实现这一目标的最简单方法吗?

1 个答案:

答案 0 :(得分:6)

您可以对符合stride(through:by:)协议的任何内容使用stride(to:by:)Strideable。第一个包含列出的值,第二个在它之前停止。

示例:

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.")
}

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