How to remove an element from an array in Swift
Solution 1:
The let
keyword is for declaring constants that can't be changed. If you want to modify a variable you should use var
instead, e.g:
var animals = ["cats", "dogs", "chimps", "moose"]
animals.remove(at: 2) //["cats", "dogs", "moose"]
A non-mutating alternative that will keep the original collection unchanged is to use filter
to create a new collection without the elements you want removed, e.g:
let pets = animals.filter { $0 != "chimps" }
Solution 2:
Given
var animals = ["cats", "dogs", "chimps", "moose"]
Remove first element
animals.removeFirst() // "cats"
print(animals) // ["dogs", "chimps", "moose"]
Remove last element
animals.removeLast() // "moose"
print(animals) // ["cats", "dogs", "chimps"]
Remove element at index
animals.remove(at: 2) // "chimps"
print(animals) // ["cats", "dogs", "moose"]
Remove element of unknown index
For only one element
if let index = animals.firstIndex(of: "chimps") {
animals.remove(at: index)
}
print(animals) // ["cats", "dogs", "moose"]
For multiple elements
var animals = ["cats", "dogs", "chimps", "moose", "chimps"]
animals = animals.filter(){$0 != "chimps"}
print(animals) // ["cats", "dogs", "moose"]
Notes
- The above methods modify the array in place (except for
filter
) and return the element that was removed. - Swift Guide to Map Filter Reduce
- If you don't want to modify the original array, you can use
dropFirst
ordropLast
to create a new array.
Updated to Swift 5.2
Solution 3:
The above answers seem to presume that you know the index of the element that you want to delete.
Often you know the reference to the object you want to delete in the array. (You iterated through your array and have found it, e.g.) In such cases it might be easier to work directly with the object reference without also having to pass its index everywhere. Hence, I suggest this solution. It uses the identity operator !==
, which you use to test whether two object references both refer to the same object instance.
func delete(element: String) {
list = list.filter { $0 !== element }
}
Of course this doesn't just work for String
s.
Solution 4:
Swift 5: Here is a cool and easy extension to remove elements in an array, without filtering :
extension Array where Element: Equatable {
// Remove first collection element that is equal to the given `object`:
mutating func remove(object: Element) {
guard let index = firstIndex(of: object) else {return}
remove(at: index)
}
}
Usage :
var myArray = ["cat", "barbecue", "pancake", "frog"]
let objectToRemove = "cat"
myArray.remove(object: objectToRemove) // ["barbecue", "pancake", "frog"]
Also works with other types, such as Int
since Element
is a generic type:
var myArray = [4, 8, 17, 6, 2]
let objectToRemove = 17
myArray.remove(object: objectToRemove) // [4, 8, 6, 2]