Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to increase String.Index in swift3?

Tags:

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.

like image 495
San San Avatar asked Nov 03 '16 11:11

San San


People also ask

How to increase string index in Swift?

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.

What is a string index in Swift?

Index. A position of a character or code unit in a string.


1 Answers

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 
like image 141
dfrib Avatar answered Dec 12 '22 20:12

dfrib