Swift 数组中的负索引

Negative indices in Swift arrays

让数组中的第一个索引从负数而不是 0 开始是否可能且容易?

如果是这样,我将如何定义以下内容以便它们从 -1 而不是 0 开始?我如何访问该值?

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

您可以为其定义自定义下标:

extension Array {
    private var customIndexOffset: Int { return -1 }

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

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