Removing a specific object from an Array in Swift

Published on: January 10, 2020

Arrays in Swift are powerful and they come with many built-in capabilities. One of these capabilities is the ability to remove objects. If you want to remove a single, specific object from an Array and you know its index, you can use remove(at:) to delete that object:

var array = [1, 2, 3]
array.remove(at: 0) // array is now [2, 3]

If you don't know the object's position in the Array and the Array's elements conform to Equatable, you can look up the first index of the object you're looking for with firstIndex(of:) and you can then proceed to delete the item at that position:

var array = ["hello", "world"]
if let index = array.firstIndex(of: "hello") {
  array.remove(at: index) // array is now ["world"]
}

Note that this will only remove a single object, so if you have an array with repeating values you will only remove the first match:

var array = ["hello", "world", "hello"]
if let index = array.firstIndex(of: "hello") {
  array.remove(at: index) // array is now ["world", "hello"]
}

If you want to remove all matches for an object, you can use the closure based removeAll(where:):

var array = ["hello", "world"]
array.removeAll { value in
  return value == "hello"
}
// array is now ["world"]

The closure you pass to removeAll(where:) is executed for every element in the Array. When you return true from the closure, the element is removed from the Array. When you return false, the element remains in the Array.

Performance of removing elements from an array

While using removeAll(where:) is convenient, its performance is worse than using firstIndex(of:) to find an index and then removing the element using remove(at:) since firstIndex(of:) stops iterating your array as soon as a match is found while removeAll(where:) keeps iterating until it processed all items in your array. So while removeAll(where:) is more convenient to use, firstIndex(of:) alongside remove(at:) are better for performance.

If you have any questions about this tip, or if you spot inaccuracies or have feedback for me, don't hesitate to reach out on X or Threads!

Subscribe to my newsletter