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

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何在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)
}

以上是关于如何在Swift 4中增加Index.String类型的变量?的主要内容,如果未能解决你的问题,请参考以下文章