ios - 检查对象是否超出数组范围的最佳方法

标签 ios arrays swift

检查数组中特定索引处的对象是否存在(在边界内)的最佳做法是什么?

如果能像这样简单就好了,但不幸的是这是不可能的:

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/

相关文章:

arrays - 在c中使用堆栈对int数组进行排序

swift - 浮点协议(protocol)中的文字数字

ios - 如何通过 Post 方法使用 JSON 模型将 JSON 字典作为参数传递?

iphone - 如何检查EKCalendar是否可见

c - 如何在 C 中的动态双指针中存储一行

ios - 如何拦截 UITextView 中链接上的电话号码单击(调用按钮)?

swift - 通过 KeyWindow 将 XIB 作为 UIView 呈现和删除

ios - swift 4 : Set local notification once

iphone - 如何使用ASIHttpRequest创建请求,如下所示?

c - 通过循环打印一维数组未按预期工作