Preventing Index out of Range with Safe in Swift

Tolga Taner
2 min readJul 3, 2022
Photo by Maxwell Nelson on Unsplash

Safe provides bounds-checking for existing collections in Swift. It prevents Index out of range error when we deal with for instance accessing collection’s element to show for every table view or collection view. It unwraps the value of collection if it is not inside it, gives a nil value. Therefore, it is type safe. Let’s look at how we do in O(1) performance.

Let’s create a subscript in Array bounds. It takes an index parameter and returns an element if it is possible, otherwise returns nil.

To achieve that completely, we need to create an array which name is Worker and create its array with worker data.

Let’s try to access both all elements of worker array and any index is not in.

As we can see, we have to access elements inside workers array and there is no value corresponding to second index. With safe keyword, it returns nil. If we don’t prefer safe keyword here, our application unfortunately is crashed.

That’s all for now, I think, using safe keyword saves our life to prevent any crashing when we encounter any complex structure that we want to show. Thanks for reading.