How to increase String.Index in swift3?
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
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)