Swift 3.0 iterate over String.Index range

Iterating over characters in a string is cleaner in Swift 4:

let myString = "Hello World"    
for char in myString {
    print(char)
}

Use the following:

for i in s.characters.indices[s.startIndex..<s.endIndex] {
  print(s[i])
}

Taken from Migrating to Swift 2.3 or Swift 3 from Swift 2.2


You can traverse a string by using indices property of the characters property like this:

let letters = "string"
let middle = letters.index(letters.startIndex, offsetBy: letters.characters.count / 2)

for index in letters.characters.indices {

    // to traverse to half the length of string 
    if index == middle { break }  // s, t, r

    print(letters[index])  // s, t, r, i, n, g
}

From the documentation in section Strings and Characters - Counting Characters:

Extended grapheme clusters can be composed of one or more Unicode scalars. This means that different characters—and different representations of the same character—can require different amounts of memory to store. Because of this, characters in Swift do not each take up the same amount of memory within a string’s representation. As a result, the number of characters in a string cannot be calculated without iterating through the string to determine its extended grapheme cluster boundaries.

emphasis is my own.

This will not work:

let secondChar = letters[1] 
// error: subscript is unavailable, cannot subscript String with an Int

Another option is to use enumerated() e.g:

let string = "Hello World"    
for (index, char) in string.characters.enumerated() {
    print(char)
}

or for Swift 4 just use

let string = "Hello World"    
for (index, char) in string.enumerated() {
    print(char)
}

Tags:

Swift

Swift3