NEW: Nominations are now open for the 2019 Swift Community Awards! >>

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…

SAVE 20% ON iOS CONF SG The largest iOS conference in Southeast Asia is back in Singapore for the 5th time in January 2020, now with two days of workshops plus two days of talks on SwiftUI, Combine, GraphQL, and more! Save a massive 20% on your tickets by clicking on this link.

MASTER SWIFT NOW
Buy Testing Swift Buy Practical iOS 12 Buy Pro Swift Buy Swift Design Patterns Buy Swift Coding Challenges Buy Server-Side Swift (Vapor Edition) Buy Server-Side Swift (Kitura Edition) Buy Hacking with macOS Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with Swift Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers 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