5

I have a string, which chars I need to iterate. I also need to track the current position, so I created a variable position of a type String.Index.

But when I want to increment the position value I get an error: "Binary operator '+=' cannot be applied to operands of type 'String.Index' and 'Int'"

class Lex {

var position: String.Index

init(input: String) {
    self.input = input
    self.position = self.input.startIndex
}

func advance() {
    assert(position < input.endIndex, "Cannot advance past the end!")
    position += 1 //Binary operator '+=' cannot be applied to operands of type 'String.Index' and 'Int'
}
...//rest

I understand the error, which states that I can't increment by integer a variable of type Index.String. But how do I get the index then?

1

1 Answer 1

8

Don't think in terms of Int, think in terms of index.

func advance() {
    assert(position < input.endIndex, "Cannot advance past the end!")
    position = input.index(after: position)
}

or

func advance() {
    assert(position < input.endIndex, "Cannot advance past the end!")
    input.formIndex(after: &position)
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much! I am a novice in Swift. It helped me a lot.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.