是否有一个函数,我可以使用迭代数组,并有索引和元素,像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)") }
其他回答
基本枚举
for (index, element) in arrayOfValues.enumerate() {
// do something useful
}
或者用Swift 3…
for (index, element) in arrayOfValues.enumerated() {
// do something useful
}
枚举,过滤和映射
但是,我最常将enumerate与map或filter结合使用。例如,在一对数组上操作。
在这个数组中,我想过滤奇数或偶数索引元素,并将它们从整型转换为双精度。所以enumerate()得到索引和元素,然后filter检查索引,最后为了去掉结果元组,我将它映射到元素。
let evens = arrayOfValues.enumerate().filter({
(index: Int, element: Int) -> Bool in
return index % 2 == 0
}).map({ (_: Int, element: Int) -> Double in
return Double(element)
})
let odds = arrayOfValues.enumerate().filter({
(index: Int, element: Int) -> Bool in
return index % 2 != 0
}).map({ (_: Int, element: Int) -> Double in
return Double(element)
})
从Swift 3开始,的确如此
for (index, element) in list.enumerated() {
print("Item \(index): \(element)")
}
斯威夫特5. x:
我个人更喜欢使用forEach方法:
list.enumerated().forEach { (index, element) in
...
}
你也可以使用简短的版本:
list.enumerated().forEach { print("index: \($0.0), value: \($0.1)") }
在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)")
}
这是枚举循环公式:
for (index, value) in shoppingList.enumerate() {
print("Item \(index + 1): \(value)")
}
更多详情请点击这里。