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

2 Answers 2

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)")
    }
    
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you, I am just learning Swift and this is all very new syntax for me.
@Biggytiny Welcome mate :) Once you understand the syntax it is looks easy for you too.
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
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.