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

问题描述 投票:0回答:1

我有一个字符串,我需要迭代的字符。我还需要跟踪当前位置,因此我创建了一个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类型的变量。但是我怎么得到索引呢?

swift string indexing
1个回答
4
投票

不要用Int来思考,用index来思考。

func advance() {
    assert(position < input.endIndex, "Cannot advance past the end!")
    position = input.index(after: position)
}
© www.soinside.com 2019 - 2024. All rights reserved.