在Array中的特定索引处检查对象是否存在(在边界内)的最佳实践是什么?
让它像这样简单会很好,但不幸的是,这是不可能的:
let testArray = ["A", "B", "C", "D"]
if let result = testArray[6] {
println("Result: \(result)")
}
else {
println("Result does not exist. Out of bounds.")
}
Run Code Online (Sandbox Code Playgroud)
我是否需要检查总数?
谢谢!
Ale*_*erg 18
您还可以对Array进行扩展,这样您就可以使用if-let进行检查:
extension Array {
func at(index: Int) -> Element? {
if index < 0 || index > self.count - 1 {
return nil
}
return self[index]
}
}
let arr = [1, 2, 3]
if let value = arr.at(index: 2) {
print(value)
}
Run Code Online (Sandbox Code Playgroud)
您可以将该~=运算符与该indices函数结合使用,该函数是创建容器的完整索引范围范围的快捷方式:
let a = [1,2,3]
let idx = 3 // one past the end
if indices(a) ~= idx {
println("within")
}
else {
println("without")
}
Run Code Online (Sandbox Code Playgroud)
需要注意的一点是,它适用于具有可比索引的任何类型的容器,而不仅仅是具有整数索引的数组.将索引视为数字通常是一个很好的习惯,因为它可以帮助您更一般地思考没有这些索引的容器上的算法,例如字符串或字典:
let s = "abc"
let idx = s.endIndex
idx < count(s) // this won't compile
idx < s.startIndex // but this will
// and so will this
if indices(s) ~= idx {
println("within")
}
else {
println("without")
}
Run Code Online (Sandbox Code Playgroud)
算法越普遍,您就越有可能将它们分解为泛型并增加重复使用.
| 归档时间: |
|
| 查看次数: |
3390 次 |
| 最近记录: |