1

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)")
}
Biggytiny
  • 519
  • 10
  • 29

2 Answers2

6

You have two ways to get your desired output.

  1. 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])")
    }
    
  2. Using enumerated() with for in and where.

    for (index,item) in testArray2.enumerated() where index % 2 == 0 {
        print("position \(index) : \(item)")
    }
    
Nirav D
  • 71,513
  • 12
  • 161
  • 183
3

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
}
Palle
  • 11,511
  • 2
  • 40
  • 61