gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 10:09:35 24 4
gpt4 key购买 nike

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

关于swift - 如何在 Swift 4 中增加 Index.String 类型的变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49709205/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com