Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 842
Jojodmo Avatar asked Mar 24 '16 05:03

Jojodmo


2 Answers

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
like image 116
Sulthan Avatar answered Nov 15 '22 07:11

Sulthan


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)
}
like image 23
user3441734 Avatar answered Nov 15 '22 06:11

user3441734