Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
504 views
in Technique[技术] by (71.8m points)

arrays - Swift for循环:用于索引,数组中的元素?(Swift for loop: for index, element in array?)

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

(有没有可以用来遍历数组并具有索引和元素的函数,例如python的enumerate?)

for index, element in enumerate(list):
    ...
  ask by thinker3 translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

(从Swift 3.0开始,如果需要每个元素的索引及其值,则可以使用enumerated()方法遍历数组。)

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)")
}

Before Swift 3.0 and after Swift 2.0, the function was called enumerate() :

(在Swift 3.0之前和Swift 2.0之后,该函数称为enumerate() :)

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

Prior to Swift 2.0, enumerate was a global function.

(在Swift 2.0之前, enumerate是一个全局函数。)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...