如何在 Swift 4 中增加 Index.String 类型的变量?

rom*_*_ds 2 string indexing swift

我有一个字符串,我需要迭代哪些字符。我还需要跟踪当前位置,因此我创建了一个 String.Index 类型的变量位置。

但是当我想增加位置值时,我收到一个错误:“二元运算符 '+=' 不能应用于类型为 'String.Index' 和 '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
Run Code Online (Sandbox Code Playgroud)

我理解错误,它指出我不能按整数递增 Index.String 类型的变量。但是我如何获得索引呢?

vad*_*ian 6

不要从 方面Int考虑,从 方面考虑index

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

或者

func advance() {
    assert(position < input.endIndex, "Cannot advance past the end!")
    input.formIndex(after: &position)
}
Run Code Online (Sandbox Code Playgroud)