Using String.CharacterView.Index.successor() in for statements

In the future, C-style for statements will be removed from Swift. While there are many alternate methods to using the C-style for statements, such as using stride, or the ..< operator, these only work in some conditions

For example, in older versions of swift, it was possible to loop through every other one of the indexes, String.CharacterView.Index, of a String using C-style for statements

  • Why isn't convertible to ?
  • Can't form Range with end < start Check range before doing for loop?
  • How to separate attributes from a NSAttributed String and apply these attributes on other string?
  • Swift 2.2 breaks optionals/unwrapping optionals
  • How to rewrite Swift ++ operator in ?: ternary operator
  • How to use a variadic closure in swift?
  • for var index = string.startIndex; index < string.endIndex; index = string.successor().successor(){
        //code
    }
    

    Yet this is now deprecated. There is a way to do the same thing, using a while loop

    var index = string.startIndex
    while index < string.endIndex{
        //code
    
        index = index.successor().successor()
    }
    

    but it isn’t much more than a workaround. There is the ..< operator, which would be perfect for looping through every index of the string

    for index in string.startIndex..<string.endIndex
    

    Yet this doesn’t help with looping through every other index of the string, or every nth index of the string

    Is there any more “swifty” way of looping through every other index of a String other than a while loop? This question doesn’t just pertain to string indexes, but just objects that have functions such as .successor() in general, where stride and ..< don’t work.

    2 Solutions Collect From Internet About “Using String.CharacterView.Index.successor() in for statements”

    you can use ‘stepping’

    let str = "abcdefgh"
    for i in str.characters.indices where str.startIndex.distanceTo(i) % 2 == 0 {
        print(i,str.characters[i])
    }
    

    prints

    0 a
    2 c
    4 e
    6 g
    

    UPDATE, based on Sulthan’s notes

    for (i,v) in str.characters.enumerate() where i % 2 == 0 {
        print(i, v)
    }
    

    Let’s do it with functional programming:

    let text = "abcdefgh"
    
    text.characters
        .enumerate()  // let's get integer index for every character
        .filter { (index, element) in index % 2 == 0 }  // let's filter out every second character
        .forEach { print($0, $1) } // print
    

    Result:

    0 a
    2 c
    4 e
    6 g