是否有一个函数,我可以使用迭代数组,并有索引和元素,像Python的枚举?
for index, element in enumerate(list):
...
是否有一个函数,我可以使用迭代数组,并有索引和元素,像Python的枚举?
for index, element in enumerate(list):
...
当前回答
这是枚举循环公式:
for (index, value) in shoppingList.enumerate() {
print("Item \(index + 1): \(value)")
}
更多详情请点击这里。
其他回答
从Swift 2开始,需要对集合调用enumerate函数,如下所示:
for (index, element) in list.enumerate() {
print("Item \(index): \(element)")
}
在函数式编程中像这样使用. enumeration ():
list.enumerated().forEach { print($0.offset, $0.element) }
从Swift 3开始,的确如此
for (index, element) in list.enumerated() {
print("Item \(index): \(element)")
}
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
斯威夫特5. x:
我个人更喜欢使用forEach方法:
list.enumerated().forEach { (index, element) in
...
}
你也可以使用简短的版本:
list.enumerated().forEach { print("index: \($0.0), value: \($0.1)") }