1

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?

2
  • for char in myString.characters { // stuff }. Commented Sep 16, 2017 at 22:04
  • @rmaddy, thanks for the answer! But as I mentioned, I need to implement methods like hasNext () and getNextChar (), and not a for loop that will do all the job... Commented Sep 16, 2017 at 22:08

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.