向后循环循环[重复]

问题描述 投票:3回答:1

是否可以创建倒置的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中最简单的方法?

swift for-loop iteration
1个回答
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.")
}

您也可以使用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.")
}
© www.soinside.com 2019 - 2024. All rights reserved.