我正在使用forEach
语句,但我想将其转换为for-loop
. 但是,for-loop
现在不推荐使用 C 样式。
这是我要转换的内容:
items.indices.forEach { fromIndex in
...
}
如何使用for-loop
前向兼容的?
您可以尝试以下方法之一:
let arr = ["a", "b", "c", "d", "e", "f", "g"]
let startIndex = 3
let increment = 2
for var i in startIndex..<arr.count {
print(arr[i], terminator: " ") //d e f g
}
for i in startIndex.stride(to: arr.count, by: increment) {
print(i, terminator: " ") //d f
}
for (index, element) in arr.enumerate() {
print(index, terminator: " ") //d f a b c d e f g
}
这是我发现的一篇关于 Swift 2.2 更改的好文章。
至于您的问题,如果您想使用传统的 c 样式循环,新语法将是:
for var i in 0..<items.indices.count {
print("index: \(i)")
}