Swift – Remove Element from Array

In this tutorial, we will learn how to remove an element from the Swift Array.

To remove an element from the Swift Array, use array.remove(at:index) method.

Remember that the index of an array starts at 0. If you want to remove ith element use the index as (i-1).

Example 1: Remove an element at ith index in the array

In this example, we have an Integer array of size 7 and we shall delete 4th element using remove(at:index) method.

main.swift

var numbers:[Int] = [2, 3, 5, 7, 11, 13, 17]

numbers.remove(at: 3)

numbers.forEach { number in
    print("\(number)")
}

Output

2
3
5
11
13
17

Example 2: Remove last element of the array

In this example, we have an Integer array of size 4 and we shall delete the last element using remove(at: array.count-1) method.

main.swift

var months:[String] = ["January", "February", "March", "April"]

months.remove(at: months.count-1)

months.forEach { month in
    print("\(month)")
}

Output

January
February
March

Example 3: Remove first element of the array

In this example, we have a String Array and we shall remove the first element using remove(at:0) method.

main.swift

var months:[String] = ["January", "February", "March", "April"]

months.remove(at: 0)

months.forEach { month in
    print("\(month)")
}

Output

February
March
April

Conclusion

In this Swift Tutorial, we have learned how to delete or remove an element from array with the help of Swift example programs.