Reputation: 529
Is there a way to use a for-in loop through an array of strings by an index greater than 1 using .enumerated() and stride, in order to keep the index and the value?
For example, if I had the array
var testArray2: [String] = ["a", "b", "c", "d", "e"]
and I wanted to loop through by using testArray2.enumerated() and also using stride by 2 to output:
0, a
2, c
4, e
So ideally something like this; however, this code will not work:
for (index, str) in stride(from: 0, to: testArray2.count, by: 2){
print("position \(index) : \(str)")
}
Upvotes: 1
Views: 5935
Reputation: 12109
To iterate with a stride, you could use a where
clause:
for (index, element) in testArray2.enumerated() where index % 2 == 0 {
// do stuff
}
Another possible way would be to map from indices to a collection of tuples of indices and values:
for (index, element) in stride(from: 0, to: testArray2.count, by: 2).map({($0, testArray2[$0])}) {
// do stuff
}
Upvotes: 3
Reputation: 72410
You have two ways to get your desired output.
Using only stride
var testArray2: [String] = ["a", "b", "c", "d", "e"]
for index in stride(from: 0, to: testArray2.count, by: 2) {
print("position \(index) : \(testArray2[index])")
}
Using enumerated()
with for in
and where
.
for (index,item) in testArray2.enumerated() where index % 2 == 0 {
print("position \(index) : \(item)")
}
Upvotes: 6