是否有一个函数,我可以使用迭代数组,并有索引和元素,像Python的枚举?
for index, element in enumerate(list):
...
是否有一个函数,我可以使用迭代数组,并有索引和元素,像Python的枚举?
for index, element in enumerate(list):
...
当前回答
如果你出于某种原因想要一个更传统的查找循环,通过索引访问数组中的元素:
let xs = ["A", "B", "C", "D"]
for i in 0 ..< xs.count {
print("\(i) - \(xs[i])")
}
输出:
0 - A
1 - B
2 - C
3 - D
其他回答
我们调用枚举函数来实现这个。就像
for (index, element) in array.enumerate() {
index is indexposition of array
element is element of array
}
在函数式编程中像这样使用. enumeration ():
list.enumerated().forEach { print($0.offset, $0.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
对于那些想使用forEach的人。
斯威夫特4
extension Array {
func forEachWithIndex(_ body: (Int, Element) throws -> Void) rethrows {
try zip((startIndex ..< endIndex), self).forEach(body)
}
}
Or
array.enumerated().forEach { ... }