arrays - 我可以快速覆盖下标吗?
问题描述
我想在 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?
解决方案
您不能覆盖现有的下标,原因有两个:
- 结构不支持继承和方法覆盖,句号
- 即使他们这样做了,这也会破坏现有的代码,这不会期望结果是可选的。
相反,只需定义一个新的扩展:
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
推荐阅读
- apache-superset - 自定义整个 Apache Superset UI
- ruby-on-rails - throw :warden 并不总是被 failure_app 抓住
- azure - ARM 模板的输出可以在另一个模板中用作不称为嵌套的引用吗?
- .net - 本地使用 DotNet 的一天中的几个小时
- javascript - 从字符串中删除最后一个 + 符号的正则表达式是什么
- css - 在反应视图上将代码部署到heroku时未显示库样式
- excel-formula - 使用 Excel 进行数据分析
- angular - 导航到库源代码而不是索引
- python - Python 电子邮件侦听器时间间隔,仅下载 .pdf 和 .doc 附件
- javascript - 在 Vuejs 应用程序中集成 basic-ftp npm 包