swift for loop: for index, element in array?

有没有一个函数可以用来遍历一个数组,并有索引和元素,就像python的枚举一样?

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

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

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

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 3 provides a method called enumerated() for Array . enumerated() has the following declaration:

func enumerated() -> EnumeratedSequence<Array<Element>>

Returns a sequence of pairs (n, x), where n represents a consecutive integer starting at zero, and x represents an element of the sequence.


In the simplest cases, you may use enumerated() with a for loop. For example:

let list = ["Car", "Bike", "Plane", "Boat"]
for (index, element) in list.enumerate() {
    print(index, ":", element)
}

/*
prints:
0 : Car
1 : Bike
2 : Plane
3 : Boat
*/

Note however that you're not limited to use enumerated() with a for loop. In fact, if you plan to use enumerated() with a for loop for something similar to the following code, you're doing it wrong:

let list = [Int](1...5)
var arrayOfTuples = [(Int, Int)]()

for (index, element) in list.enumerated() {
    arrayOfTuples += [(index, element)]
}

print(arrayOfTuples) // prints [(0, 1), (1, 2), (2, 3), (3, 4), (4, 5)]

The correct way to do this is:

let list = [Int](1...5)
let arrayOfTuples = Array(list.enumerated())
print(arrayOfTuples) // prints [(0, 1), (1, 2), (2, 3), (3, 4), (4, 5)]

As an alternative, you may also use enumerated() with map :

let list = [Int](1...5)
let arrayOfDictionaries = list.enumerated().map { (a, b) in return [a : b] }
print(arrayOfDictionaries) // prints [[0: 1], [1: 2], [2: 3], [3: 4], [4: 5]]

Moreover, although it has some limitations, forEach can be a good replacement to a for loop:

let list = [Int](1...5)
list.reversed().enumerated().forEach { print($0, ":", $1) }

/*
prints:
0 : 5
1 : 4
2 : 3
3 : 2
4 : 1
*/

By using enumerated() and makeIterator() , you can even iterate manually on your Array . For example:

import UIKit

class ViewController: UIViewController {

    var generator = ["Car", "Bike", "Plane", "Boat"].enumerated().makeIterator()

    // Link this IBAction to a UIButton in your storyboard
    @IBAction func iterate(_ sender: UIButton) {
        let tuple: (offset: Int, element: String)? = generator.next()
        print(String(describing: tuple))
    }

}

/*
 Will print the following lines for 6 `touch up inside`:
 Optional((0, "Car"))
 Optional((1, "Bike"))
 Optional((2, "Plane"))
 Optional((3, "Boat"))
 nil
 nil
 */

从Swift 2开始,需要在集合上调用枚举函数,如下所示:

for (index, element) in list.enumerate() {
    print("Item (index): (element)")
}
链接地址: http://www.djcxy.com/p/19268.html

上一篇: 翻译:显示翻译为动态找到的翻译密钥

下一篇: swift for循环:索引,数组中的元素?