如果我在Swift中有一个数组,并且试图访问一个超出范围的索引,那么会出现一个毫不奇怪的运行时错误:
var str = ["Apple", "Banana", "Coconut"]
str[0] // "Apple"
str[3] // EXC_BAD_INSTRUCTION
然而,我本以为,在Swift带来的所有可选链接和safety的情况下,做以下事情是微不足道的:
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
.
我try 添加自己的subscript()
实现,但我不确定如何将调用传递给原始实现,或者如何在不使用下标符号的情况下访问项目(基于索引):
extension Array {
subscript(var index: Int) -> AnyObject? {
if index >= self.count {
NSLog("Womp!")
return nil
}
return ... // What?
}
}