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]
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]
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] }
}