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

In the future, C-style for operators will be removed from Swift . Although there are many alternative methods for using C-style statements for statements, such as stridestatements or statements ..<, they work only in certain conditions.

For example, in earlier versions of swift, you could scroll through all the other indices of String.CharacterView.Indexa String string using the C-style for operators

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

But it is now out of date. There is a way to do the same using a loopwhile

var index = string.startIndex
while index < string.endIndex{
    //code

    index = index.successor().successor()
}

but this is nothing more than a workaround. There is a statement ..<that is perfect for scrolling through each row index

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

n-

"" , while? , , .successor() , stride ..< .

+4
2

"stepping"

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

0 a
2 c
4 e
6 g

,

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

:

let text = "abcdefgh"

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

:

0 a
2 c
4 e
6 g
+4

All Articles