Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to check if object is out of bounds in array

Tags:

arrays

ios

swift

What is the best practice to check if an object exists (is within bounds) at a specific index in an Array?

It would be nice to have it as simple as this, but that is unfortunately not possible:

let testArray = ["A", "B", "C", "D"]

if let result = testArray[6] {
    println("Result: \(result)")
}
else {
    println("Result does not exist. Out of bounds.")
}

Will I have to check against the total count?

Thank you!

like image 341
fisher Avatar asked Oct 17 '25 08:10

fisher


2 Answers

You could also make an extension to Array, so you will be able to check with 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)
}
like image 182
Aleksi Sjöberg Avatar answered Oct 19 '25 22:10

Aleksi Sjöberg


You can use the ~= operator in conjunction with the indices function, which is a shortcut for creating a range of the full index range of a container:

let a = [1,2,3]
let idx = 3  // one past the end

if indices(a) ~= idx {
    println("within")
}
else {
    println("without")
}

The one thing to note is this works with any kind of container that has a comparable index, not just ones like array that have integer indices. Thinking of indices as numbers is generally a good habit to get out of, since it helps you think more generally about algorithms on containers without these indices, such as strings or dictionaries:

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")
}

The more general your algorithms, the more chance you will be able to factor them out into generics and increase re-use.

like image 37
Airspeed Velocity Avatar answered Oct 19 '25 20:10

Airspeed Velocity



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!