gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 14:15:30 24 4
gpt4 key购买 nike

如果我在 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's answer对于这个问题有很好的建议和解决方案,但是,我碰巧偶然发现了实现此功能的更好方法:

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
}
}
<小时/>

示例

let array = [1, 2, 3]

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

关于xcode - Swift 中通过可选绑定(bind)进行安全(边界检查)数组查找?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31245062/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com