OneBite.Dev - Coding blog in a bite size

Remove A Specific Element From An Array In Swift

Code snippet for how to Remove A Specific Element From An Array In Swift with sample and detail explanation

When dealing with arrays in Swift, it’s quite common to want to remove a specific element. This article provides an example of how to do just that. We will walk through a quick code snippet and then explain it step by step for better understanding.

Code snippet for removing a specific element from an array in Swift

Here’s an example. Let’s assume you want to remove the number 3 from an array of integers.

var array = [1, 2, 3, 4, 5]
if let index = array.firstIndex(of: 3) {
    array.remove(at: index)
}

In this code, array is initialized with the integers from 1 to 5. We then remove the number 3 from the array.

Code explanation for removing a specific element from an array in Swift

In the code snippet above, we start by establishing an array. The firstIndex(of:) function is used to find the first index in array where the specified value (3) appears. This function returns the index as an optional because the specified value might not be in the array.

What follows is an if let statement which is a form of optional binding in Swift. The idea behind optional binding is to check if an optional contains a value, and if it does, to assign this value to a temporary constant or variable.

So, if the specified value (3) is found in the array, its index is unwrapped from the optional and assigned to the constant index. The remove(at:) function is then used to remove the item at this index.

In conclusion, this code finds the first occurrence of 3 in the array and removes it. Please note that if 3 appears more than once in the array, only the first occurrence will be removed. If you want to remove all occurrences of 3, you will need to either use a loop or filter method.

swift