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?
You can't override the existing subscript, for two reasons:
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