arrays - 我可以快速覆盖下标吗?

标签 arrays swift overriding subscript

<分区>


我想进行有效性检查并快速返回数组中的适当值,如下面的函数 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?

最佳答案

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

  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

关于arrays - 我可以快速覆盖下标吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58229140/

相关文章:

arrays - 如何在rails 3中获取二维数组的行和列长度?

swift 2 : Error handling: throw: How to pass an object with an error?

ios - 如何防止嵌入导航 Controller 的 View Controller 中的自动旋转?

java子类有方法返回它的类

c++ - 在 C++ 中重写基的重载函数

javascript - 在不触及非唯一值的情况下,通过拼接和推送将数组替换为另一个数组

python - 如何同时修改numpy数组的N列?

python - 基于元素函数将 1d numpy 数组映射到 2d 数组

swift - 怎么check for not nil pass

Ruby 覆盖数组类的初始化方法