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

其他回答

从Swift 2开始,需要对集合调用enumerate函数,如下所示:

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

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

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

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

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

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 { ... }