当前位置: 首页 > 面试题库 >

通过可选绑定在Swift中进行安全(边界检查)数组查找?

孟翰藻
2023-03-14
问题内容

如果我在Swift中有一个数组,并尝试访问超出范围的索引,那么将出现一个令人惊讶的运行时错误:

var str = ["Apple", "Banana", "Coconut"]

str[0] // "Apple"
str[3] // EXC_BAD_INSTRUCTION

但是,我本想考虑Swift带来的所有可选链接和 安全性 ,这样做很简单:

let theIndex = 3
if let nonexistent = str[theIndex] { // Bounds check + Lookup
    print(nonexistent)
    ...do other things with nonexistent...
}

代替:

let theIndex = 3
if (theIndex < str.count) {         // Bounds check
    let nonexistent = str[theIndex] // Lookup
    print(nonexistent)   
    ...do other things with nonexistent... 
}

但这不是事实-我必须使用ol’ if语句检查并确保索引小于str.count

我尝试添加自己的subscript()实现,但是不确定如何将调用传递给原始实现,或在不使用下标符号的情况下访问项目(基于索引):

extension Array {
    subscript(var index: Int) -> AnyObject? {
        if index >= self.count {
            NSLog("Womp!")
            return nil
        }
        return ... // What?
    }
}

问题答案:

Alex的回答为该问题提供了很好的建议和解决方案,但是,我偶然发现了一种更好的实现此功能的方法:

Swift 3.2及更高版本

extension Collection {

    /// Returns the element at the specified index if it is within bounds, otherwise nil.
    subscript (safe index: Index) -> Element? {
        return indices.contains(index) ? self[index] : nil
    }
}

Swift 3.0和3.1

extension Collection where Indices.Iterator.Element == Index {

    /// Returns the element at the specified index if it is within bounds, otherwise nil.
    subscript (safe index: Index) -> Generator.Element? {
        return indices.contains(index) ? self[index] : nil
    }
}

感谢Hamish提出了Swift 3解决方案。

迅捷2

extension CollectionType {

    /// Returns the element at the specified index if it is within bounds, otherwise nil.
    subscript (safe index: Index) -> Generator.Element? {
        return indices.contains(index) ? self[index] : nil
    }
}

let array = [1, 2, 3]

for index in -20...20 {
    if let item = array[safe: index] {
        print(item)
    }
}


 类似资料:
  • 问题内容: 我正在尝试检查2D数组中每个元素的相邻值,但是当我到达数组的边或角落时,得到了IndexOutOfBoundsException。例如,如果我的数组是: | 2 | 4 | 2 | 7 | 8 | | 8 | 1 | 0 | 5 | 6 | | 0 | 3 | 1 | 5 | 2 | | 1 | 9 | 7 | 2 | 0 | 我知道8的所有邻居都是7,5和6,但是我的陈述并没有正确检

  • 通过系统内置规则,将匹配规则的安全性较低的资源扫描出来并按照建议进行处理,从而提高系统安全性的目的。 建议列表 建议列表显示所有匹配优化建议规则的资源列表,用户可根据建议对资源进行处理。 忽略列表 忽略列表显示不需要处理的资源或一类规则建议。 规则配置 规则配置即根据系统内影响资源安全的条件设置相应的规则,如安全组的规则设置等,当资源匹配规则则表示资源的安全性较低,需要用户进行处理等。

  • 我有这样的要求: http://localhost:4000/services/querywithdsl?min=30 我的域实体仅包含id: 和我的Rest控制器与谓词 存储库: 我想用querydsl构建查询,就像这个使用绑定的查询 我找到的所有示例都是将查询参数直接映射到实体列,但在这个示例中,我的实体中只有一个id,我想对传入的参数值进行范围检查,这些参数值的名称与实体列的名称不同。 然而

  • 问题内容: 我一直在寻找通过Linux中的命令行查找具有相同名称的正在运行的进程数的最佳方法。例如,如果我想查找正在运行的bash进程数并获得“ 5”。目前,我有一个脚本执行’pidof’,然后对标记化字符串进行计数。这工作正常,但我想知道是否有更好的方法可以完全通过命令行来完成。在此先感谢您的帮助。 问题答案: 在可用的系统上,该选项返回与给定名称匹配的进程数的计数 请注意,这是-style匹配

  • 在小米生态云建立的安全边界内,生态链企业的业务与数据将得到有效的安全保障。 小米安全团队会持续监控生态云上的所有域名和IP,发现问题会及时通知对应的生态链企业。 生态链企业运行在生态云上的云端业务,如有需要,可以联系小米做深度安全检测。

  • 当我使用documentId作为字段路径从Firebase Firestore查询数据时,在Web页面(javascript)和Firebase函数(node.js)中运行脚本时,我会得到不同的行为。 给我一个错误: 错误:{错误:__name__上的筛选器必须是clientreadablestream._emitstatusIfdone(/user_code/node_modules/fireb