Scrungepipes
Scrungepipes

Reputation: 37600

In swift 3, how do you advance an index?

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?

Upvotes: 18

Views: 14370

Answers (2)

Sentry.co
Sentry.co

Reputation: 5619

Swift 3:

let str = "hello"
let subStr = str.substring(from:str.index(str.startIndex, offsetBy: 1))
print(subStr) // ello

Less verbose solution:

let index:Int = 1
let str = "hello"
print(str.substring(from: str.idx(index))) // ello
extension String{
    func idx(_ index:Int) -> String.Index{
        return self.index(self.startIndex, offsetBy: index)
    }
}

Upvotes: 9

rickster
rickster

Reputation: 126177

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.

Upvotes: 27

Related Questions