Search code examples
swiftfor-in-loopstrideenumerated

Swift: For Loop to iterate through enumerated array by index greater than 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)")
}

Solution

  • 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)")
      }