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.
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.
Eg:
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 (eg 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, eg <
, >
, ==
) 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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.