是否有一个函数,我可以使用迭代数组,并有索引和元素,像Python的枚举?
for index, element in enumerate(list):
...
是否有一个函数,我可以使用迭代数组,并有索引和元素,像Python的枚举?
for index, element in enumerate(list):
...
当前回答
斯威夫特5. x:
我个人更喜欢使用forEach方法:
list.enumerated().forEach { (index, element) in
...
}
你也可以使用简短的版本:
list.enumerated().forEach { print("index: \($0.0), value: \($0.1)") }
其他回答
在函数式编程中像这样使用. enumeration ():
list.enumerated().forEach { print($0.offset, $0.element) }
我们调用枚举函数来实现这个。就像
for (index, element) in array.enumerate() {
index is indexposition of array
element is element of array
}
对于你想要做的事情,你应该在你的数组上使用枚举()方法:
for (index, element) in list.enumerated() {
print("\(index) - \(element)")
}
对于那些想使用forEach的人。
斯威夫特4
extension Array {
func forEachWithIndex(_ body: (Int, Element) throws -> Void) rethrows {
try zip((startIndex ..< endIndex), self).forEach(body)
}
}
Or
array.enumerated().forEach { ... }
使用.enumerate()可以,但它不能提供元素的真实索引;它只为每个连续的元素提供一个以0开始并加1的Int值。这通常是无关紧要的,但是当与ArraySlice类型一起使用时,可能会出现意想不到的行为。取以下代码:
let a = ["a", "b", "c", "d", "e"]
a.indices //=> 0..<5
let aSlice = a[1..<4] //=> ArraySlice with ["b", "c", "d"]
aSlice.indices //=> 1..<4
var test = [Int: String]()
for (index, element) in aSlice.enumerate() {
test[index] = element
}
test //=> [0: "b", 1: "c", 2: "d"] // indices presented as 0..<3, but they are actually 1..<4
test[0] == aSlice[0] // ERROR: out of bounds
这是一个有点做作的例子,在实践中也不是一个常见的问题,但我仍然认为值得知道这是可能发生的。