cfi*_*her 3 iteration for-loop swift
是否可以创建倒置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.")
}
Run Code Online (Sandbox Code Playgroud)
什么是实现这一目标的最简单方法Swift?
您可以使用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.")
}
Run Code Online (Sandbox Code Playgroud)
您还可以使用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.")
}
Run Code Online (Sandbox Code Playgroud)