How to remove an element from an array in Swift with an example
This tutorial shows you multiple ways to delete an element from an Array in Swift.
How to remove an array element with an index? How to remove the first element from an array How to remove the last element from an array.
Array in Swift provides the following methods to remove an element.
- Remove at method
- filter method
- removeFirst method
- removeLast method
How to remove an array element in Swift?
We can remove an element using an index or an element using Array remove at the method in Swift.
Array remove(at:index)
The index is the position of the array. It removes an element at the position
First, Delete an element from the array using the index
var numbers = ["one", "two", "three", "four","five"];
numbers.remove(at: 1);
print(numbers);
Output:
["one", "three", "four", "five"]
The second approach, without an index, Remove an element from an array with a given element. First, Get an index using the findIndex
method with a given element Returns the index and passes the index to the remove method.
var numbers = ["one", "two", "three", "four","five"];
if let index = numbers.firstIndex(of: "five") {
numbers.remove(at: index)
}
print(numbers);
Output:
["one", "two", "three", "four"]
How to remove the first element from an array in swift
Array removeFirst
method removes the first element from an array in Swift.
Syntax
Array.removeFirst()
It removes and returns the first element from an array if the array is empty, It throws an Exception.
Here is an example
var numbers = ["one", "two", "three", "four","five"];
numbers.removeFirst();
print(numbers);
Output:
["two", "three", "four", "five"]
How to remove the last element from an array in swift
Array removeLast
method removes the last element from an array in swift.
Syntax
Array.removeLast()
It removes and returns the last element from an array if the array is empty, It throws an Exception.
Here is an example
var numbers = ["one", "two", "three", "four","five"];
numbers.removeLast();
print(numbers);
Output:
["one","two", "three", "four"]