NEW: Subscribe to Hacking with Swift+ and accelerate your learning! >>

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 Instabug

SPONSORED Are you tired of wasting time debugging your Swift app? Instabug’s SDK is here to help you minimize debugging time by providing you with complete device details, network logs, and reproduction steps with every bug report. All data is attached automatically, and it only takes a line of code to setup. Start your free trial now and get 3 months off exclusively for the Hacking with Swift Community.

Start your free trial!

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

BUY OUR BOOKS
Buy Pro Swift 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 (Vapor Edition) 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 Server-Side Swift (Kitura Edition) Buy Beyond Code

About the author

Paul Hudson is the creator of Hacking with Swift, the most comprehensive series of Swift books in the world. He's also the editor of Swift Developer News, the maintainer of the Swift Knowledge Base, and a speaker at Swift events around the world. If you're curious you can learn more here.

Was this page useful? Let us know!

Average rating: 4.7/5

Link copied to your pasteboard.