UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

It’s time to stop using index(of:)

firstIndex(of:) is here to stay.

Paul Hudson       @twostraws

SE-0204 added the lastIndex(of:) and lastIndex(where:) methods to the Swift standard library, while also renaming index(of:) and index(where:) to be firstIndex(of:) and firstIndex(where:) to avoid confusion.

However, even though the first… and last… methods were added as planned in Swift 4.2, index(of:) seems to have snuck under the radar and was left intact and untouched – until now, that is.

As of Swift 5.0, index(of:) and index(where:) have been formally deprecated, which means they will be removed fully at some future point in time. Past experience has shown that Swift is serious about deprecation: you can expect warnings to appear as soon as you upgrade to Xcode 10.2, and for this method to go away completely in the next 12 months or so.

So, get ahead of the game: if you search for “.index” in your code to spot any places where you might be using the old method calls, and look to replace them with the equivalent “firstIndex” call. The functionality is identical, to the point where index(of:) is actually implemented like this:

public func index(of element: Element) -> Index? {
    return firstIndex(of: element)
}

I’m busy going through my original Hacking with Swift book as part of my 100 Days of Swift initiative, and I’m on the hunt for index(…) calls. With around 6000 pages of Swift tutorials it might take a little time, but I’ll get there…

Hacking with Swift is sponsored by Essential Developer

SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until April 28th.

Click to save your free spot now

Sponsor Hacking with Swift and reach the world's largest Swift community!

BUY OUR BOOKS
Buy Pro Swift Buy Pro SwiftUI Buy Swift Design Patterns Buy Testing Swift Buy Hacking with iOS Buy Swift Coding Challenges Buy Swift on Sundays Volume One Buy Server-Side Swift Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Advanced iOS Volume Three Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with macOS Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Beyond Code

Was this page useful? Let us know!

Average rating: 4.7/5

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.