通过可选绑定在Swift中进行安全(边界检查)数组查找?
如果我在Swift中有一个数组,并尝试访问超出范围的索引,则会出现一个不足为奇的运行时错误:
var str = ["Apple", "Banana", "Coconut"]str[0] // "Apple"str[3] // EXC_BAD_INSTRUCTION
但是,我会想到Swift带来的所有可选链接和安全性,这样做会很简单:
let theIndex = 3if let nonexistent = str[theIndex] { // Bounds check + Lookup print(nonexistent)
...do other things with nonexistent...}代替:
let theIndex = 3if (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? }}
慕婉清6462132
莫回无
慕少森
随时随地看视频慕课网APP