【问题标题】:How to increase String.Index in swift3?如何在 swift3 中增加 String.Index?
【发布时间】:2016-11-03 11:07:15
【问题描述】:

在swift2.3中 ++ 运算符用于 string.index 增加

例如。 我++

我更改为 swift 3 代码发生 " 一元运算符'++'不能应用于'@lvalue String.Index'(又名'@lvalue String.CharacterView.Index')类型的操作数“在swift 3中

我重写 例如。 i += 1

但是这段代码无法解决。 请帮帮我。

【问题讨论】:

    标签: ios swift iphone swift3 operators


    【解决方案1】:

    String.IndexString.CharacterView.Index 的类型别名。该指数不能单独增加。相反,您可以在用于提取索引的CharacterView 上使用index(after:) 实例方法。

    例如:

    let str = "foobar"
    let chars = str.characters
    
    if let bIndex = chars.index(of: "b") {
        let nextIndex = chars.index(after: bIndex)
        print(str[bIndex...nextIndex]) // ba
    }
    

    或者,假设您有一个索引(例如str.startIndex),您可以使用index(_:, offsetBy:) 实例方法,该方法也可直接用于String 实例:

    let str = "foobar"
    let startIndex = str.startIndex
    let nextIndex = str.index(startIndex, offsetBy: 1)
    print(str[startIndex...nextIndex]) // fo
    

    【讨论】:

      【解决方案2】:

      String.Index 没有为它定义+++= 或任何类型的运算符(除了比较,例如<>==)。它还定义了其他用于移动索引的方法。要增加索引 1 的位置,代码如下所示:string.index(i, offsetBy: 1)

      let string = "Some string"
      var i = string.startIndex
      i = string.index(i, offsetBy: 1)
      

      【讨论】:

        猜你喜欢
        • 2017-12-15
        • 2017-02-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-01-29
        • 2017-04-07
        相关资源
        最近更新 更多