是否有一个函数,我可以用来迭代一个数组并同时具有索引和元素,如python的枚举?
for index, element in enumerate(list):
...
是。从Swift 3.0开始,如果你需要每个元素的索引及其值,你可以使用enumerated()
method迭代数组。它返回由索引和数组中每个项的值组成的对的序列。例如:
for (index, element) in list.enumerated() {
print("Item \(index): \(element)")
}
在Swift 3.0之前和Swift 2.0之后,该函数被称为enumerate()
:
for (index, element) in list.enumerate() {
print("Item \(index): \(element)")
}
在加入Swift 2.0之前,enumerate
是一个全球性的功能。
for (index, element) in enumerate(list) {
println("Item \(index): \(element)")
}
Xcode 8和Swift 3:Array可以使用tempArray.enumerated()
进行枚举
例:
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
对于那些想要使用forEach
的人。
斯威夫特4
extension Array {
func forEachWithIndex(_ body: (Int, Element) throws -> Void) rethrows {
try zip((startIndex ..< endIndex), self).forEach(body)
}
}
要么
array.enumerated().forEach { ... }
为了完整性,您可以简单地遍历数组索引并使用下标来访问相应索引处的元素:
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])
}
使用集合enumerated()
方法。请注意,它返回带有offset
和element
的元组集合:
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 enumeratedIndices(body: ((index: Index, element: Element)) throws -> ()) rethrows {
var index = startIndex
for element in self {
try body((index,element))
formIndex(after: &index)
}
}
}
测试:
let list = ["100","200","300","400","500"]
list.dropFirst(2).enumeratedIndices {
print("Index:", $0.index, "Element:", $0.element)
}
这将打印
指数:2元素:300
指数:3元素:400
指数:4元素:500
我个人更喜欢使用forEach
方法:
list.enumerated().forEach { (index, element) in
...
}
您也可以使用简短版本:
list.enumerated().forEach { print("index: \($0.0), value: \($0.1)") }
对于您想要做的事情,您应该在数组上使用enumerated()
方法:
for (index, element) in list.enumerated() {
print("\(index) - \(element)")
}
我们调用了枚举函数来实现它。喜欢
for(index,element)in array.enumerate(){
// index是数组的索引位置
// element是数组的元素
}
Swift 5为enumerated()
提供了一种名为Array
的方法。 enumerated()
有以下声明:
func enumerated() -> EnumeratedSequence<Array<Element>>
返回一对(n,x)序列,其中n表示从零开始的连续整数,x表示序列的元素。
在最简单的情况下,您可以使用带有for循环的enumerated()
。例如:
let list = ["Car", "Bike", "Plane", "Boat"]
for (index, element) in list.enumerated() {
print(index, ":", element)
}
/*
prints:
0 : Car
1 : Bike
2 : Plane
3 : Boat
*/
但请注意,您不限于使用带有for循环的enumerated()
。事实上,如果你计划使用带有for循环的enumerated()
来实现类似于以下代码的东西,那么你做错了:
let list = [Int](1...5)
var arrayOfTuples = [(Int, Int)]()
for (index, element) in list.enumerated() {
arrayOfTuples += [(index, element)]
}
print(arrayOfTuples) // prints [(0, 1), (1, 2), (2, 3), (3, 4), (4, 5)]
更快捷的方法是:
let list = [Int](1...5)
let arrayOfTuples = Array(list.enumerated())
print(arrayOfTuples) // prints [(offset: 0, element: 1), (offset: 1, element: 2), (offset: 2, element: 3), (offset: 3, element: 4), (offset: 4, element: 5)]
作为替代方案,您也可以使用enumerated()
和map
:
let list = [Int](1...5)
let arrayOfDictionaries = list.enumerated().map { (a, b) in return [a : b] }
print(arrayOfDictionaries) // prints [[0: 1], [1: 2], [2: 3], [3: 4], [4: 5]]
此外,虽然它有一些limitations,forEach
可以很好地替代for循环:
let list = [Int](1...5)
list.reversed().enumerated().forEach { print($0, ":", $1) }
/*
prints:
0 : 5
1 : 4
2 : 3
3 : 2
4 : 1
*/
通过使用enumerated()
和makeIterator()
,您甚至可以在Array
上手动迭代。例如:
import UIKit
import PlaygroundSupport
class ViewController: UIViewController {
var generator = ["Car", "Bike", "Plane", "Boat"].enumerated().makeIterator()
override func viewDidLoad() {
super.viewDidLoad()
let button = UIButton(type: .system)
button.setTitle("Tap", for: .normal)
button.frame = CGRect(x: 100, y: 100, width: 100, height: 100)
button.addTarget(self, action: #selector(iterate(_:)), for: .touchUpInside)
view.addSubview(button)
}
@objc func iterate(_ sender: UIButton) {
let tuple = generator.next()
print(String(describing: tuple))
}
}
PlaygroundPage.current.liveView = ViewController()
/*
Optional((offset: 0, element: "Car"))
Optional((offset: 1, element: "Bike"))
Optional((offset: 2, element: "Plane"))
Optional((offset: 3, element: "Boat"))
nil
nil
nil
*/
从Swift 2开始,需要在集合上调用枚举函数,如下所示:
for (index, element) in list.enumerate() {
print("Item \(index): \(element)")
}
我在寻找使用Dictionary的方法时找到了这个答案,事实证明它很容易适应它,只需传递元素的元组。
// Swift 2
var list = ["a": 1, "b": 2]
for (index, (letter, value)) in list.enumerate() {
print("Item \(index): \(letter) \(value)")
}
for (index, element) in arrayOfValues.enumerate() {
// do something useful
}
或者使用Swift 3 ......
for (index, element) in arrayOfValues.enumerated() {
// do something useful
}
但是,我经常使用枚举与map或filter结合使用。例如,在几个阵列上运行。
在这个数组中,我想过滤奇数或偶数索引元素,并将它们从Ints转换为Doubles。所以enumerate()
获取索引和元素,然后过滤器检查索引,最后摆脱生成的元组我将它映射到元素。
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)
})
您可以简单地使用枚举循环来获得所需的结果:
斯威夫特2:
for (index, element) in elements.enumerate() {
print("\(index): \(element)")
}
Swift 3&4:
for (index, element) in elements.enumerated() {
print("\(index): \(element)")
}
或者你可以简单地通过for循环来获得相同的结果:
for index in 0..<elements.count {
let element = elements[index]
print("\(index): \(element)")
}
希望能帮助到你。
从Swift 3开始,它是
for (index, element) in list.enumerated() {
print("Item \(index): \(element)")
}
这是枚举循环的公式:
for (index, value) in shoppingList.enumerate() {
print("Item \(index + 1): \(value)")
}
有关详细信息,请查看Here。
使用.enumerate()
工作,但它不提供元素的真实索引;它只提供一个以0开头的Int,并为每个连续的元素递增1。这通常是无关紧要的,但与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
这是一个有点人为的例子,它在实践中并不是一个常见的问题,但我认为值得知道这可能发生。