如果我在Swift中有一个数组,并尝试访问超出范围的索引,则会出现一个不足为奇的运行时错误:
var str = ["Apple", "Banana", "Coconut"]
str[0] // "Apple"
str[3] // EXC_BAD_INSTRUCTION
Run Code Online (Sandbox Code Playgroud)
但是,我会想到Swift带来的所有可选链接和安全性,这样做会很简单:
let theIndex = 3
if let nonexistent = str[theIndex] { // Bounds check + Lookup
print(nonexistent)
...do other things with nonexistent...
}
Run Code Online (Sandbox Code Playgroud)
代替:
let theIndex = 3
if (theIndex < str.count) { // Bounds check
let nonexistent = str[theIndex] // Lookup
print(nonexistent)
...do other things with nonexistent...
}
Run Code Online (Sandbox Code Playgroud)
但事实并非如此 - 我必须使用ol' if语句来检查并确保索引小于str.count.
我尝试添加自己的subscript()实现,但我不知道如何将调用传递给原始实现,或者不使用下标符号来访问项目(基于索引):
extension Array {
subscript(var index: Int) …Run Code Online (Sandbox Code Playgroud)