是否有一个函数,我可以使用迭代数组,并有索引和元素,像Python的枚举?
for index, element in enumerate(list):
...
是否有一个函数,我可以使用迭代数组,并有索引和元素,像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)")
}
其他回答
对于那些想使用forEach的人。
斯威夫特4
extension Array {
func forEachWithIndex(_ body: (Int, Element) throws -> Void) rethrows {
try zip((startIndex ..< endIndex), self).forEach(body)
}
}
Or
array.enumerated().forEach { ... }
从Swift 2开始,需要对集合调用enumerate函数,如下所示:
for (index, element) in list.enumerate() {
print("Item \(index): \(element)")
}
在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)")
}
在函数式编程中像这样使用. enumeration ():
list.enumerated().forEach { print($0.offset, $0.element) }
使用.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
这是一个有点做作的例子,在实践中也不是一个常见的问题,但我仍然认为值得知道这是可能发生的。