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

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

当前回答

斯威夫特5. x:

Let list = [0,1,2,3,4,5]

list.enumerated().forEach { (index, value) in
    print("index: \(index), value: \(value)")
}

Or,

list.enumerated().forEach { 
    print("index: \($0.offset), value: \($0.element)")
} 

Or,

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

其他回答

从Swift 3开始,的确如此

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

基本枚举

for (index, element) in arrayOfValues.enumerate() {
// do something useful
}

或者用Swift 3…

for (index, element) in arrayOfValues.enumerated() {
// do something useful
}

枚举,过滤和映射

但是,我最常将enumerate与map或filter结合使用。例如,在一对数组上操作。

在这个数组中,我想过滤奇数或偶数索引元素,并将它们从整型转换为双精度。所以enumerate()得到索引和元素,然后filter检查索引,最后为了去掉结果元组,我将它映射到元素。

let evens = arrayOfValues.enumerate().filter({
                            (index: Int, element: Int) -> Bool in
                            return index % 2 == 0
                        }).map({ (_: Int, element: Int) -> Double in
                            return Double(element)
                        })
let odds = arrayOfValues.enumerate().filter({
                            (index: Int, element: Int) -> Bool in
                            return index % 2 != 0
                        }).map({ (_: Int, element: Int) -> Double in
                            return Double(element)
                        })

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

在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, value) in shoppingList.enumerate() {
print("Item \(index + 1): \(value)")
}

更多详情请点击这里。