首页 > 解决方案 > 我可以快速覆盖下标吗?

问题描述


我想在 swift 中进行有效性检查并在数组中返回适当的值,例如下面的函数 objectFromArr(at:)。

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

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

我不想使用函数。因为 swift Array 通常使用下标来获取对象。所以,如果可能的话,我想覆盖下标。

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

to

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

标签: arraysswiftoverridingsubscript

解决方案


您不能覆盖现有的下标,原因有两个:

  1. 结构不支持继承和方法覆盖,句号
  2. 即使他们这样做了,这也会破坏现有的代码,这不会期望结果是可选的。

相反,只需定义一个新的扩展:

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

推荐阅读