Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In swift 3, how do you advance an index?

Tags:

ios

swift

I've trying to get a substring of a string starting from index 1 in iOS 10 beta 6, and its a headache as swifts strings are constantly changing and much documentation is out of date and useless.

String has the substring(from:Index), but it can't accept an integer (which has been the case for a while), so I was planning to use startIndex and advance it by 1, but now Index has no advanceBy method, so I cannot do this:

let aString = "hello"
let subString = aString.substring(from: aString.startIndex.advanceBy(1))

How can I get a substring from index 1? How can you advance an index these days, and what is the point of the substring(from Index) method - how are you supposed to use it?

like image 854
Gruntcakes Avatar asked Aug 16 '16 21:08

Gruntcakes


1 Answers

Looks pretty clear as the first item in the Swift 3 migration guide:

The most visible change is that indexes no longer have successor(), predecessor(), advancedBy(_:), advancedBy(_:limit:), or distanceTo(_:) methods. Instead, those operations are moved to the collection, which is now responsible for incrementing and decrementing its indices.

myIndex.successor()  =>  myCollection.index(after: myIndex)
myIndex.predecessor()  =>  myCollection.index(before: myIndex)
myIndex.advance(by: …) => myCollection.index(myIndex, offsetBy: …)

So it looks like you want something like:

let greeting = "hello"
let secondCharIndex = greeting.index(after: greeting.startIndex)
let enryTheEighthGreeting = greeting.substring(from: secondCharIndex) // -> "ello"

(Note also that if you want Collection functionality—like index management—on a String, it sometimes helps to use its characters view. String methods like startIndex and index(after:) are just conveniences that forward to the characters view. That part isn't new, though... Strings stopped being Collections themselves in Swift 2 IIRC.)

There's more about the collection indexes change in SE-0065 - A New Model for Collections and Indices.

like image 137
rickster Avatar answered Oct 28 '22 15:10

rickster