Remove instances of an object from an Array in Swift

Published by donnywals on

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.

If you have any questions about this tip, or if you spot inaccuracies or have feedback for me, don't hesitate to send me a Tweet!


Practical Combine

Learn everything you need to know about Combine and how you can use it in your projects with my new book Practical Combine. You'll get thirteen chapters, a Playground and a handful of sample projects to help you get up and running with Combine as soon as possible.

The book is available as a digital download for just $24.99!

Get Practical Combine

Receive weekly updates about my posts

Categories: Swift Tips