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