检查数组中特定索引处的对象是否存在(在边界内)的最佳做法是什么?
如果能像这样简单就好了,但不幸的是这是不可能的:
let testArray = ["A", "B", "C", "D"]
if let result = testArray[6] {
println("Result: \(result)")
}
else {
println("Result does not exist. Out of bounds.")
}
我需要检查总数吗?
谢谢!
最佳答案
你也可以对 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)
}
关于ios - 检查对象是否超出数组范围的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29605708/