本文翻译自: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):
...
#1楼
参考:https://stackoom.com/question/1cotB/Swift-for循环-用于索引-数组中的元素
#2楼
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)")
}
#3楼
I found this answer while looking for a way to do that with a Dictionary , and it turns out it's quite easy to adapt it, just pass a tuple for the element. 我在寻找使用Dictionary做到这一点的方法时找到了这个答案,事实证明,调整它非常容易,只需为元素传递一个元组即可。
// Swift 2
var list = ["a": 1, "b": 2]
for (index, (letter, value)) in list.enumerate() {
print("Item \(index): \(letter) \(value)")
}
#4楼
Starting with Swift 2, the enumerate function needs to be called on the collection like so: 从Swift 2开始,需要在集合上调用枚举函数,如下所示:
for (index, element) in list.enumerate() {
print("Item \(index): \(element)")
}
#5楼
Swift 5 provides a method called enumerated()
for Array
. Swift 5为Array
提供了一种称为enumerated()
的方法。 enumerated()
has the following declaration: enumerated()
具有以下声明:
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. 返回一个成对的序列(n,x),其中n代表一个从零开始的连续整数,x代表该序列的一个元素。
In the simplest cases, you may use enumerated()
with a for loop. 在最简单的情况下,可以将enumerated()
与for循环一起使用。 For example: 例如:
let list = ["Car", "Bike", "Plane", "Boat"]
for (index, element) in list.enumerated() {
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. 但是请注意,您不限于将enumerated()
与for循环一起使用。 In fact, if you plan to use enumerated()
with a for loop for something similar to the following code, you're doing it wrong: 实际上,如果您打算将enumerated()
与for循环一起使用,类似于以下代码,则您做错了:
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)]
A swiftier way to do this is: 一个更快的方法是:
let list = [Int](1...5)
let arrayOfTuples = Array(list.enumerated())
print(arrayOfTuples) // prints [(offset: 0, element: 1), (offset: 1, element: 2), (offset: 2, element: 3), (offset: 3, element: 4), (offset: 4, element: 5)]
As an alternative, you may also use enumerated()
with map
: 另外,您也可以将enumerated()
与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: 而且,尽管它有一些局限性 ,但是forEach
可以很好地替代for循环:
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
. 通过使用enumerated()
和makeIterator()
,您甚至可以在Array
上手动进行迭代。 For example: 例如:
import UIKit
import PlaygroundSupport
class ViewController: UIViewController {
var generator = ["Car", "Bike", "Plane", "Boat"].enumerated().makeIterator()
override func viewDidLoad() {
super.viewDidLoad()
let button = UIButton(type: .system)
button.setTitle("Tap", for: .normal)
button.frame = CGRect(x: 100, y: 100, width: 100, height: 100)
button.addTarget(self, action: #selector(iterate(_:)), for: .touchUpInside)
view.addSubview(button)
}
@objc func iterate(_ sender: UIButton) {
let tuple = generator.next()
print(String(describing: tuple))
}
}
PlaygroundPage.current.liveView = ViewController()
/*
Optional((offset: 0, element: "Car"))
Optional((offset: 1, element: "Bike"))
Optional((offset: 2, element: "Plane"))
Optional((offset: 3, element: "Boat"))
nil
nil
nil
*/
#6楼
This is the Formula of loop of Enumeration: 这是枚举循环的公式:
for (index, value) in shoppingList.enumerate() {
print("Item \(index + 1): \(value)")
}