Hello people, Leo here. The topic today is how to Safe get a value from an array in Swift.

Why this is important? Well, if you don’t have a mechanism to safe get values from your arrays, one day your app can crash in production because you didn’t cover all the edge cases for your Array usage.

Today we’ll explore how can we get values from an array while avoiding crashes in your app.

So let’s go!

 

Problem – How to Safe get a Value From an Array in Swift

I want to get a value from array but I don’t want by any chance get an array out of bounds error.

First, let’s examine the below code:

let nameList = ["Ana","Leo","Bob"]

print(nameList[3])

Arrays in Swift are zero-based, which means we’re trying to print the fourth element of the *nameList*.

If you run the above code you get an:

So how can we be sure when accessing an array that the index/element is there?

If you know what you are searching for, you can use *contains()* method that will return a Boolean if it’s there or not:

let nameList = ["Ana","Leo","Bob"]
nameList.contains("Ana") // returns true

You can check if the index that you’re searching for is between the existing index inside the array, as the code below shows:

let targetIndex = 3

if nameList.startIndex <= targetIndex && targetIndex < nameList.endIndex {
    print(nameList[targetIndex])
} else {
    print("can't get from array because index out of bounds")
}

And furthermore, you can extract the if code to a function to be more readable:

func isValid(index: Int, to array: [Any]) -> Bool {
    array.startIndex <= index && index < array.endIndex
}

if isValid(index: targetIndex, to: nameList) {
    print(nameList[targetIndex])
} else {
    print("can't get from array because index out of bounds")
}

This works great and if you aren’t dealing with a lot of arrays in your codebase can be a way to go.

 

Using Array’s extensions to Safe get a Value From an Array

We can improve this just by using a custom extension subscript to the array, this way all arrays in the code could utilize this feature.

The code below is one way to do that:

extension Array {
subscript(safe index: Int) -> Element? {
    guard index < endIndex, index >= startIndex else { return nil}
        return self[index]
    }
}

Or using the indices ( thanks Cícero):

extension Array { subscript(safe index: Int) -> Element? { guard indices ~= index else { return nil } return self[index] } }

The drawback of this approach is those subscript returns an optional so you’ll have to do the nil check after.

And that’s it.

 

Summary

Today we studied how to Safe get a value from an array in Swift in two ways, one using a helper function and another one using the extension and returning an Optional value. What is the best? Well, you have to judge by yourself, both work and it is your turn to make a decision on what to use.

That’s all my people, I hope you liked reading this article as much as I enjoyed writing it. If you want to support this blog you can Buy Me a Coffee or leave a comment saying hello. You can also sponsor posts and I’m open to freelance writing! You can reach me on LinkedIn or Twitter and send me an e-mail through the contact page.

Thanks for the reading and… That’s all folks.

Credits – image