是否有一个函数,我可以使用迭代数组,并有索引和元素,像Python的枚举?

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

当前回答

在iOS 8.0/Swift 4.0+

你可以使用forEach 根据苹果文档:

返回一个对序列(n, x),其中n表示从0开始的连续整数,x表示序列中的一个元素。

let numberWords = ["one", "two", "three"]

numberWords.enumerated().forEach { (key, value) in
   print("Key: \(key) - Value: \(value)")
}

其他回答

从Swift 2开始,需要对集合调用enumerate函数,如下所示:

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

我在寻找一种使用Dictionary的方法时找到了这个答案,结果证明它很容易适应,只需为元素传递一个元组。

// Swift 2

var list = ["a": 1, "b": 2]

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

在iOS 8.0/Swift 4.0+

你可以使用forEach 根据苹果文档:

返回一个对序列(n, x),其中n表示从0开始的连续整数,x表示序列中的一个元素。

let numberWords = ["one", "two", "three"]

numberWords.enumerated().forEach { (key, value) in
   print("Key: \(key) - Value: \(value)")
}

我们调用枚举函数来实现这个。就像

    for (index, element) in array.enumerate() {
     index is indexposition of array
     element is element of array 
   }

使用.enumerate()可以,但它不能提供元素的真实索引;它只为每个连续的元素提供一个以0开始并加1的Int值。这通常是无关紧要的,但是当与ArraySlice类型一起使用时,可能会出现意想不到的行为。取以下代码:

let a = ["a", "b", "c", "d", "e"]
a.indices //=> 0..<5

let aSlice = a[1..<4] //=> ArraySlice with ["b", "c", "d"]
aSlice.indices //=> 1..<4

var test = [Int: String]()
for (index, element) in aSlice.enumerate() {
    test[index] = element
}
test //=> [0: "b", 1: "c", 2: "d"] // indices presented as 0..<3, but they are actually 1..<4
test[0] == aSlice[0] // ERROR: out of bounds

这是一个有点做作的例子,在实践中也不是一个常见的问题,但我仍然认为值得知道这是可能发生的。