Skip to content
DeveloperMemos

How to Avoid Out of Bounds Errors When Getting Items from an Array in Swift

Swift, Arrays, Runtime Errors2 min read

When working with arrays in Swift, it's common to retrieve items from specific indexes within the array. However, if you're not careful, it's easy to accidentally access an index that doesn't exist, resulting in an "out of bounds" error. In this article, we'll explore some techniques for avoiding these errors and writing safer, more robust code.

  1. Check the array bounds manually

One simple way to avoid out of bounds errors is to check the bounds of the array manually before accessing any items. For example, consider the following code:

1let arr = [1, 2, 3, 4, 5]
2
3if index >= 0 && index < arr.count {
4 let item = arr[index]
5 // Do something with item
6} else {
7 // Handle the out of bounds case
8}

In this example, we check if the index is within the bounds of the array before accessing the item at that index. If the index is out of bounds, we can handle the error appropriately. While this technique can work, it can be tedious to manually check the bounds every time you access an array item.

  1. Use the "if let" statement

Another approach is to use the "if let" statement to safely access an array item. The "if let" statement is a way to safely unwrap an optional value in Swift. In the context of arrays, we can use it to safely access an array item at a specific index. Here's an example:

1let arr = [1, 2, 3, 4, 5]
2
3if let item = arr[safe: index] {
4 // Do something with item
5} else {
6 // Handle the out of bounds case
7}

In this example, we define an extension on the Array type that adds a "safe" subscript. This subscript returns an optional value, which will be nil if the index is out of bounds. By using the "if let" statement to unwrap the optional value, we can safely access the array item without worrying about out of bounds errors.

Here's the implementation of the "safe" subscript:

1extension Array {
2 subscript(safe index: Index) -> Element? {
3 return indices.contains(index) ? self[index] : nil
4 }
5}

This implementation checks if the index is within the bounds of the array using the "indices" property, which returns a Range of all valid indices for the array. If the index is within the bounds, we return the corresponding array item. Otherwise, we return nil.

  1. Use the "guard" statement

The "guard" statement is another way to handle out of bounds errors in Swift. Like the "if let" statement, it's a way to safely unwrap an optional value. However, it's typically used in cases where you want to exit a function or method early if a condition is not met. Here's an example:

1func doSomething(with arr: [Int], at index: Int) {
2 guard index >= 0 && index < arr.count else {
3 // Handle the out of bounds case
4 return
5 }
6
7 let item = arr[index]
8 // Do something with item
9}

In this example, we use the "guard" statement to check if the index is within the bounds of the array. If it's not, we handle the out of bounds case and exit the function early using the "return" statement. If the index is within the bounds, we can safely access the array item and perform some operation with it.

When working with arrays in Swift, it's important to be mindful of out of bounds errors. By using techniques like manual bounds checking, the "if let" statement , and the "guard" statement, you can write safer, more robust code that avoids these errors. While each technique has its own advantages and disadvantages, they all share the goal of preventing runtime errors and improving the reliability of your code.