我可以覆盖 swift 中的下标吗?
Can I override subscript in swift?
我想在 swift 中的数组中进行有效性检查和 return 适当的值,如下面的函数 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?
您不能覆盖现有的下标,原因有二:
- 结构不支持继承和方法覆盖,期间
- 即使他们这样做了,这也会破坏现有代码,这不会期望结果是可选的。
相反,只需定义一个新扩展:
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
我想在 swift 中的数组中进行有效性检查和 return 适当的值,如下面的函数 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?
您不能覆盖现有的下标,原因有二:
- 结构不支持继承和方法覆盖,期间
- 即使他们这样做了,这也会破坏现有代码,这不会期望结果是可选的。
相反,只需定义一个新扩展:
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