Swift循环倒序遍历

3

是否可能创建一个反向的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中,最简单的实现方式是什么?


请参见 https://dev59.com/QWAf5IYBdhLWcg3wlDYD,使用 by 可以控制范围的步长。 - Scriptable
1个回答

10

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

示例:

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

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接