{

How to remove an element from an array in swift with 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 index or 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 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"]
THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.