SWIFT for循环:索引,元素数组? [英] swift for loop: for index, element in array?

查看:120
本文介绍了SWIFT for循环:索引,元素数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有我可以用它来遍历一个数组的同时具有指标和元素,如Python的枚举函数?

 对于指数,在枚举(列表)元素:
    ...


解决方案

是的。由于雨燕2.0​​的,如果您需要为每个元素的索引,其值一起,你可以使用<$c$c>enumerate()方法遍历数组。它返回一个的索引和用于阵列中的每个项目的值组成的元组。例如:

 为(索引,元素)的list.enumerate(){
    打印(项目\\(指数):\\(元素))
}

此前雨燕2.0​​,枚举是一个全球性的功能。

 在枚举(列表)(索引,元素){
    的println(项目\\(指数):\\(元素))
}

Is there a function that I can use to iterate over an array with a for having both index and element, like python's enumerate?

for index, element in enumerate(list):
    ...

解决方案

Yes. As of Swift 2.0, if you need the index for each element along with its value, you can use the enumerate() method to iterate over the array. It returns a tuple composed of the index and the value for each item in the array. For example:

for (index, element) in list.enumerate() {
    print("Item \(index): \(element)")
}

Prior to Swift 2.0, enumerate was a global function.

for (index, element) in enumerate(list) {
    println("Item \(index): \(element)")
}

这篇关于SWIFT for循环:索引,元素数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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