Search code examples
arraysswiftoverridingsubscript

Can I override subscript in swift?



I want to do validity check and return appropriate value in array in swift, like below function objectFromArr(at:).

var arr = [10, 20, 30, 40]

func objectFromArr(at: Int) -> Int? {
    return at < 0 || at >= arr.count ? nil : arr[at]
}

I don't want to use function. Because of swift Array typically uses subscript to get object. So, I want to override subscript if possible.

@inlinable public subscript(index: Int) -> Element

to

override @inlinable public subscript(index: Int) -> Element?

Solution

  • You can't override the existing subscript, for two reasons:

    1. Structs don't support inheritance and method overrides, period
    2. Even if they did, this would break existing code, which wouldn't expect the result to be optional.

    Instead, just define a new extension:

    extension Collection {
        subscript(safelyAccess index: Index) -> Element? {
            get { return self.indices.contains(index) ? self[index] : nil }
        }
    }
    
    let a = [1, 2, 3]
    print(a[safelyAccess: 99]) // => nil