Cleanest way to wrap array index?

Viewed 2837

Say I have an array of 5 Ints. What would be the most efficient way to wrap the index of the array if the index were incremented or decremented (for example) the following occurs?

where n = 0: arr[n-1] // -> arr[4] (wraps from 0 back to the end of the array)

where n = 2: arr[n+1] // -> arr[3] (behaves as normal)

where n = 4: arr[n+1] // -> arr[0] (wraps to 0 from the end of the array)

3 Answers

A bit late to the party, but if you're facing the same issue and have a lot of use cases for wrap-around array indices, you could also put the %-solution from the accepted answer in a simple subscript extension of Array, like so:

extension Array {
    subscript (wrapping index: Int) -> Element {
        return self[(index % self.count + self.count) % self.count]
    }
}

Example Usage:

let array = ["a","b","c"]
print( array[wrapping: 0] )   // a
print( array[wrapping: 4] )   // b
print( array[wrapping: -1] )  // c

Cleanest I can do for only positive integers is this

extension Array{
    subscript(wrapAround index: Int) -> Element {
        return self[index % self.count]
    }
}
Related