4

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?

rmaddy
  • 314,917
  • 42
  • 532
  • 579
roman_ds
  • 190
  • 1
  • 17
  • 1
    Compare https://stackoverflow.com/q/39676939/2976878 – though in your case you can also say `input.formIndex(after: &position)`. – Hamish Apr 07 '18 at 16:04

1 Answers1

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)
}
vadian
  • 274,689
  • 30
  • 353
  • 361