How to increase String.Index in swift3?

10,768

Solution 1

String.Index is a typealias for String.CharacterView.Index. The index cannot, on its own, be increased. Rather, you can use the index(after:) instance method on the CharacterView that you used to extract the index.

E.g.:

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
}

Or, given that you have an index (e.g. str.startIndex), you can use the index(_:, offsetBy:) instance method available also directly for String instances:

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

Solution 2

String.Index doesn't have a ++, +=, or any kind of operator (other than comparisons, e.g. <, >, ==) defined for it. It has other methods defined for moving the index. To increase the index 1 position, the code would look like this: string.index(i, offsetBy: 1)

let string = "Some string"
var i = string.startIndex
i = string.index(i, offsetBy: 1)
Share:
10,768
San San
Author by

San San

Updated on June 25, 2022

Comments

  • San San
    San San almost 2 years

    In swift2.3 ++ operator use for string.index increase

    eg. i++

    I changed to swift 3 that code happen " Unary operator '++' cannot be applied to an operand of type '@lvalue String.Index' (aka '@lvalue String.CharacterView.Index') " in swift 3

    I rewrite eg. i += 1

    but this code can't solve. Please Help me.