如何在 Swift 中使用索引和元素迭代循环 [英] How to iterate a loop with index and element in Swift

查看:26
本文介绍了如何在 Swift 中使用索引和元素迭代循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一个函数可以用来遍历数组并同时具有索引和元素,例如 Python 的 enumerate?

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 开始,如果您需要每个元素的索引及其值,您可以使用 enumerated() 方法来迭代数组.它返回由索引和数组中每个项目的值组成的对序列.例如:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆