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

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

当前回答

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

其他回答

斯威夫特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)")
}

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

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

这是枚举循环公式:

for (index, value) in shoppingList.enumerate() {
print("Item \(index + 1): \(value)")
}

更多详情请点击这里。

如果你出于某种原因想要一个更传统的查找循环,通过索引访问数组中的元素:

let xs = ["A", "B", "C", "D"]

for i in 0 ..< xs.count {
    print("\(i) - \(xs[i])")
}

输出:

0 - A
1 - B
2 - C
3 - D

从Swift 3开始,的确如此

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