In this Swift tutorial, you are going to learn about the Array remove() method with some simple examples.
The Swift remove()
method removes an element of an array at the given index. We have to provide the index as an argument for the method.
remove()
methodBelow is given the syntax of the remove()
method:
array.remove(at: index)
In the above syntax:
array
is the object of an Array
class.index
is the index position of the array element that you want to remove. It must be the valid index of the array.The remove()
method returns the element of the array that was removed. The array will be modified and form a new array with the element for the specified index omitted.
Below is an example of using the Array remove()
method:
var colors = ["Green", "Pink", "Yellow", "Red"]
print("Before removing the element",colors)
var removedElement = colors.remove(at: 2)
print("After removing element",colors)
print("Removed element",removedElement)
Output:
Before removing the element ["Green", "Pink", "Yellow", "Red"]
After removing element ["Green", "Pink", "Red"]
Removed element Yellow
In the above example, we have used the remove()
method to remove the element Yellow
from our array.
If we print the array after applying the remove()
method, it shows that the element at the specified index is not present.
The variable removedElement
has stored the removed element. So we can see the removed element Yellow when we print the variable.
If we don’t need to store the removed element and only need the array after performing the task, then we don’t need to create a variable:
var colors = ["Green", "Pink", "Yellow", "Red"]
print("Before removing the element",colors)
colors.remove(at: 2)
print("After removing element",colors)
Output:
Before removing the element ["Green", "Pink", "Yellow", "Red"]
After removing element ["Green", "Pink", "Red"]
Also, read: Remove the last element from an array in Swift