0


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?
strawnut
  • 359
  • 5
  • 21
  • This is actually a broader different question than the duplicate, even though the example itself is addressed by the duplicate. – Paul Beusterien Dec 29 '21 at 20:07
  • Well the question is adequately answered so there seems little purpose in reopening it. – matt Dec 31 '21 at 16:37

1 Answers1

3

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
Alexander
  • 59,041
  • 12
  • 98
  • 151
  • Ok, Thank you Alexander. I didn't know that can use parameter name to subscript parameter. – strawnut Oct 04 '19 at 07:03
  • Great! and you can apply it in a class like ` class MyClass: NSObject, Sequence { private var _array: [DisplayedEntry] = [] subscript(index: Int) -> DisplayedEntry? { get { return self._etfEntries.indices.contains(index) ? self._etfEntries[index] : nil } }} ` – tontonCD Sep 04 '21 at 15:23