Remove element from an array by value in Swift

This tutorial is all about removing elements from an array by value in Swift. In this tutorial, we will first create an array of integer type which will contain certain elements then we will find its index value, and using its index value we will remove the element and then print the updated array.

In swift, the syntax to create an array is

var arrayname:[Int] = [firstintvalue, secondintvalue, thirdintvalue]

var digits:[Int] = [1,2,3,4,5,6]

Using this syntax we will create an array, the next step is to find out the index where the element to be removed is stored.

We will do this task using an if statement where it will check the value and its index and then we will fetch the index and remove the element at that particular index.

The syntax for this statement is-

if let index = digits.firstIndex(of: 4) {
    digits.remove(at: index)
}

As we have completed the task, we just need to print the array. We will do this using

print(digits)

Code snippet to remove an array element by value in Swift

As of now, we have got a basic idea regarding the creation of an array, finding the index, and then removing the particular element at that index. We need to combine all the snippets and execute the code.

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

Run this program online

OUTPUT:-
[1, 2, 3, 5, 6]

As you can see the declared array is [1,2,3,4,5,6] and the output array [1, 2, 3, 5, 6] has a major difference, element 4 is removed. How does that happen?

It searched the element first then it fetched its index, using that index value we have removed that element.

Thanks for reading! I hope you found this tutorial helpful, feel free to comment and share your reviews.

Leave a Reply

Your email address will not be published.