Search code examples
arraysswiftindexingindices

Negative indices in Swift arrays


Is it possible and easy to have the first index in an array to start on a negative number instead of 0?

If so, how would I define the following so these start on -1 instead of 0? And how do I access the value?

var myIntArray:[Int] = [4, 2, 1]
var myDoubleArray:[Double] = [28, 28, 14]
var myCGFloatArray:[CGFloat] = [0.14, 0.14, 0.1]

Solution

  • You can define a custom subscript for that:

    extension Array {
        private var customIndexOffset: Int { return -1 }
    
        subscript(customIndex index: Int) -> Element {
            get {
                return self[index - customIndexOffset]
            }
            set {
                self[index - customIndexOffset] = newValue
            }
        }
    }
    

    Now myIntArray[customIndex: -1] == myIntArray[0]

    - More generic, wider coverage:

    extension MutableCollection where Index == Int {
        private var customIndexOffset: Int { -2 }
    
        subscript(customIndex index: Int) -> Element {
            get { self[index - customIndexOffset] }
            set { self[index - customIndexOffset] = newValue }
        }
    }
    
    
    extension Collection where Index == Int {
        private var customIndexOffset: Int { -2 }
    
        subscript(customIndex index: Int) -> Element { self[index - customIndexOffset] }
    }