Logo 61e73bc61c0e1780102320e879dc3cac0e29303ea8894dd8f10c942f3ba8120f

otters.io

An adorable little blog

A Successor to successor()

Thursday — April 28th, 2016

Array

Changes are heading towards collection types in Swift 3! Yesterday, the big man himself approved a proposal to rethink how collections and indices interact in Swift 3. The gist of it being: If you want to get the index of a thing in a collection, ask the collection, not another index.

To give some background on what this will affect, let’s look at how the system works right now. In Swift 2, Indices have to keep track of not only where they are but how the whole collection is structured so they can give you the next or previous index. That is hard to optimize.

In Swift 3, since collections know their structure already, the proposal is to let them traverse themselves. You want the index of an object? Ask the collection it’s in. You want the following index? Ask the collection. The previous? Ask the collection. Easy for humans to understand and easier for the optimizer to optimize.

Most existing code will remain unscathed and not need to be updated. If you have code that gets indices from other indices, such as index.successor() and index.predecessor(), you will need to change to getting an index from the collection. When Swift 3 comes out, the change should look something like this:

// Before:
let luckyNumbers = [42, 7, 13, 33, 25]
var index = luckyNumbers.startIndex
let nextIndex = index.successor()

// After:
let luckyNumbers = [42, 7, 13, 33, 25]
var index = luckyNumbers.startIndex
let nextIndex = luckyNumbers.index(after: index)

This change reads easier by my eyes. More importantly, because it keeps information about the structure of the collection in the logic of the collection, indices don’t need to keep tabs on what your collection type looks like. 👍