是否有一个函数,我可以使用迭代数组,并有索引和元素,像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)")
}

斯威夫特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 list.enumerated() {
    print("\(index) - \(element)")
}

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

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

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

输出:

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

为了完整起见,你可以简单地遍历你的数组下标,并使用下标访问对应下标处的元素:

let list = [100,200,300,400,500]
for index in list.indices {
    print("Element at:", index, " Value:", list[index])
}

使用forEach

list.indices.forEach {
    print("Element at:", $0, " Value:", list[$0])
}

使用集合枚举()方法。注意,它返回一个包含偏移量和元素的元组集合:

for item in list.enumerated() {
    print("Element at:", item.offset, " Value:", item.element)
}

使用forEach:

list.enumerated().forEach {
    print("Element at:", $0.offset, " Value:", $0.element)
}

这些会打印出来

元素:0值:100 元素在:1值:200 元素在:2值:300 元素在:3值:400 元素在:4值:500

如果你需要数组索引(而不是偏移量)和它的元素,你可以扩展Collection并创建自己的方法来获取索引元素:

extension Collection {
    func indexedElements(body: ((index: Index, element: Element)) throws -> Void) rethrows {
        var index = startIndex
        for element in self {
            try body((index,element))
            formIndex(after: &index)
        }
    }
}

Alex建议的另一种可能的实现是用集合的元素压缩索引:

extension Collection {
    func indexedElements(body: ((index: Index, element: Element)) throws -> Void) rethrows {
        for element in zip(indices, self) { try body(element) }
    }
    var indexedElements: Zip2Sequence<Indices, Self> { zip(indices, self) }
}

测试:

let list =  ["100","200","300","400","500"]

// You can iterate the index and its elements using a closure
list.dropFirst(2).indexedElements {
    print("Index:", $0.index, "Element:", $0.element)
}

// or using a for loop
for (index, element) in list.indexedElements  {
    print("Index:", index, "Element:", element)
}

这将是p[print]

索引:2元素:300 指数:3元素:400 指数:4元素:500 索引:0元素:100 指数:1元素:200 索引:2元素:300 指数:3元素:400 指数:4元素:500