如果我在 Swift 中有一个数组,并尝试访问超出范围的索引,则会出现一个不足为奇的运行时错误:
var str = ["Apple", "Banana", "Coconut"]
str[0] // "Apple"
str[3] // EXC_BAD_INSTRUCTION
但是,我会想到所有可选的链接和safetySwift 带来的,做类似的事情是微不足道的:
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?
}
}
亚历克斯的回答 https://stackoverflow.com/a/25330930/1607485对于这个问题有很好的建议和解决方案,但是,我碰巧偶然发现了实现此功能的更好方法:
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
}
}
Example
let array = [1, 2, 3]
for index in -20...20 {
if let item = array[safe: index] {
print(item)
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)