检查数组CAN是否在给定索引处具有元素的快速方法?

时间:2018-04-25 19:53:09

标签: ios arrays swift

为了防止潜在的崩溃,每当我尝试访问数组中的特定元素时,我通常会进行一些安全检查。我才意识到我已经厌倦了这样做。有没有办法快速安全地完成?

var array:[String] = [/*Filled with stuff*/]
func someFunc(someIndex:Int){

    //This is unsafe. It will crash if index is negative or larger than count.
    let text = array[someIndex]

    //This is completely safe, but boring.
    let text:String
    if someIndex >= 0 && someIndex < array.count{
        text = array[someIndex] 
    }else { return }

    //What I want is something like this:
    let text = array.hasElement(at: someIndex) ? array[someIndex] : return
    //I know, I can't really put a 'return' in a statement like this, but I really want to..

    //Optimally, I'd like something like this:
    guard let text = array[someIndex] else { return }
    //But this is illegal because it's not an conditional binding with an optional type.
}

写这篇文章的时候,我意识到我可能会创建自己的Sequence或其他内容的扩展,为func hasElement(at:Int)->Bool添加一个函数。但我宁愿想要一种使用guard的方法,因为我无法进行内联condition ? true : return ..

任何单行都很感激..

2 个答案:

答案 0 :(得分:6)

Collection上的扩展名相比足够简单:

extension Collection {
    subscript(checked index: Index) -> Element? {
        if self.indices.contains(index) {
            return self[index]
        } else {
            return nil
        }
    }
}

所以:

let arr = ["Foo", "Bar", "Baz"]

print(arr[checked: 2]) // Optional("Baz")
print(arr[checked: 3]) // nil

如果这太多了,你可以使用三元运算符:

let foo: String? = arr.indices.contains(3) ? arr[3] : nil

答案 1 :(得分:0)

最简单的做法是。

extension Array {
    func haveItem(at index: Index) -> Bool {
         return index < self.count
    }
}

if yourArray.haveItem(at: 4) {
     //You have some item at index 4 in yourArray object.
}