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

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

当前回答

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

// Swift 2

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

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

其他回答

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

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

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

// Swift 2

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

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

Xcode 8和Swift 3: 可以使用temparray . enumeration()枚举数组。

例子:

var someStrs = [String]()

someStrs.append("Apple")  
someStrs.append("Amazon")  
someStrs += ["Google"]    


for (index, item) in someStrs.enumerated()  
{  
        print("Value at index = \(index) is \(item)").  
}

控制台:

Value at index = 0 is Apple
Value at index = 1 is Amazon
Value at index = 2 is Google

对于那些想使用forEach的人。

斯威夫特4

extension Array {
  func forEachWithIndex(_ body: (Int, Element) throws -> Void) rethrows {
    try zip((startIndex ..< endIndex), self).forEach(body)
  }
}

Or

array.enumerated().forEach { ... }

从Swift 3开始,的确如此

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