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



我有一个字符串,我需要迭代哪些字符。我还需要跟踪当前位置,所以我创建了一个类型为 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

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

不要

Int的角度思考,要从index的角度思考。

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

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

最新更新