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

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

当前回答

使用.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

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

其他回答

从Swift 3开始,的确如此

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

使用.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

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

对于你想要做的事情,你应该在你的数组上使用枚举()方法:

for (index, element) in list.enumerated() {
    print("\(index) - \(element)")
}

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

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

是的。从Swift 3.0开始,如果需要每个元素的索引及其值,可以使用enumeration()方法遍历数组。它返回一个由索引和数组中每个项的值组成的对序列。例如:

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

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

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

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

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