You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

解决Swift中String.Index无法直接递增的问题

嘿,这个问题我之前也踩过坑!Swift里的String.Index确实不能像整数那样直接用+=来递增,原因得从Swift字符串的设计说起——Swift的字符串是基于Unicode标量实现的,不同字符占用的内存空间并不固定(比如普通英文是1字节,emoji或者中文可能占多字节),所以String.Index并不是简单的整数偏移,而是和字符串本身绑定的特殊类型,直接加减整数编译器自然会报错。

先整理下你给出的代码片段(补上了遗漏的input属性声明):

class Lex { 
    let input: String
    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'
    }
}

正确的索引递增方式

要移动String.Index,得用字符串自带的index(_:offsetBy:)方法,它会帮你安全计算出偏移后的有效索引。修改后的advance()方法应该是这样:

func advance() {
    assert(position < input.endIndex, "Cannot advance past the end of the string")
    // 使用String的index方法完成索引递增
    position = input.index(position, offsetBy: 1)
}

额外的安全优化技巧

如果不想依赖assert来防止越界(比如希望运行时避免崩溃,优雅处理边界),可以用index(_:offsetBy:limitedBy:)方法,它会在偏移超出字符串范围时返回nil,你可以据此做容错处理:

func advanceSafely() -> Bool {
    guard let newPosition = input.index(position, offsetBy: 1, limitedBy: input.endIndex) else {
        // 已经到达字符串末尾,无法继续前进
        return false
    }
    position = newPosition
    return true
}

调用advanceSafely()时,就能通过返回值判断索引是否成功移动,避免意外崩溃。

内容的提问来源于stack exchange,提问作者roman_ds

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 08:45:32