0

我正在使用forEach语句,但我想将其转换为for-loop. 但是,for-loop现在不推荐使用 C 样式。

这是我要转换的内容:

items.indices.forEach { fromIndex in
  ...
}

如何使用for-loop前向兼容的?

4

2 回答 2

0

您可以尝试以下方法之一:

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
}
于 2016-03-24T06:07:31.237 回答
0

这是我发现的一篇关于 Swift 2.2 更改的好文章。

至于您的问题,如果您想使用传统的 c 样式循环,新语法将是:

for var i in 0..<items.indices.count {
    print("index: \(i)")
}
于 2016-03-24T06:08:38.687 回答