Search code examples
swiftstringiterator

String iterator in swift


I try to create an iterator for string processing in swift that will return every time the next chracter. But with no luck. (The final goal is to write a parser for a custom scripting language)

All methods that I found on the net involve some for loop on a range, that accesses the characters of the string, one at a time. But I rather need methods like hasNext () and getNextChar (), that other functions would call..

What is the most effective way to write an iterator class like that in swift? Is there maybe some class in swift that implements that feature already, and so, I dont have to write an iterator in the first place?


Solution

  • Call makeIterator() on the String which returns a String.Iterator. You can call next() on it to get the next character. It returns nil when there are no more characters.

    let myString = "abcde"
    
    // var iter = myString.characters.makeIterator()  // Swift 3
    var iter = myString.makeIterator()          // Swift 4 and 5
    
    while let c = iter.next() {
        print(c)
    }
    

    Output:

    a
    b
    c
    d
    e