如何在Swift中使用索引和元素迭代循环 [英] How to iterate a loop with index and element in Swift
本文介绍了如何在Swift中使用索引和元素迭代循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否有一个函数可用于遍历数组并具有索引和元素,例如Python的枚举?
Is there a function that I can use to iterate over an array and have both index and element, like Python's enumerate?
for index, element in enumerate(list):
...
推荐答案
是.从Swift 3.0开始,如果您需要每个元素的索引及其值,则可以使用
Yes. As of Swift 3.0, if you need the index for each element along with its value, you can use the enumerated()
method to iterate over the array. It returns a sequence of pairs composed of the index and the value for each item in the array. For example:
for (index, element) in list.enumerated() {
print("Item \(index): \(element)")
}
在Swift 3.0之前和Swift 2.0之后,该函数称为enumerate()
:
Before Swift 3.0 and after Swift 2.0, the function was called enumerate()
:
for (index, element) in list.enumerate() {
print("Item \(index): \(element)")
}
在Swift 2.0之前,enumerate
是全局函数.
Prior to Swift 2.0, enumerate
was a global function.
for (index, element) in enumerate(list) {
println("Item \(index): \(element)")
}
这篇关于如何在Swift中使用索引和元素迭代循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文