简体   繁体   English

如何在swift3中增加String.Index?

[英]How to increase String.Index in swift3?

In swift2.3 ++ operator use for string.index increase 在swift2.3 ++中,运算符用于string.index的增加

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 我改为swift 3代码发生“一元运算符'++'不能应用于'@lvalue String.Index'类型的操作数(又名'@lvalue String.CharacterView.Index')”在swift 3中

I rewrite eg. 我重写了例如。 i += 1 i + = 1

but this code can't solve. 但是这段代码无法解决。 Please Help me. 请帮我。

String.Index is a typealias for String.CharacterView.Index . String.Index是String.CharacterView.Index的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. 相反,您可以在用于提取索引的CharacterView上使用index(after:)实例方法。

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: 或者,假设您有一个索引(例如str.startIndex ),您可以使用也可直接用于String实例的index(_:, offsetBy:)实例方法:

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. String.Index没有为其定义的+++=或任何类型的运算符(除了比较,例如<>== )。 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) 要增加索引1的位置,代码将如下所示: string.index(i, offsetBy: 1)

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM