NEW: Master Swift design patterns with my latest book! >>

Remove all instances of an object from an array

Written by Paul Hudson    @twostraws

Arrays already have methods to find and remove a single item, or remove all items at once, but they don’t have a built-in way to remove all instances of a single item. For example, how would you remove all the 2s in the following array?

var numbers = [2, 1, 2, 3, 2, 4, 2, 5]

Fortunately we can fix this using a simple extension to Array that runs all the items through filter() and returns any that don’t match whatever item you want removed:

extension Array where Element: Equatable {
    mutating func remove(_ obj: Element) {
        self = self.filter { $0 != obj }
    }
}

Now you can write numbers.remove(2) to get back [1, 3, 4, 5].

Available from iOS 8.0

Did this solution work for you? Please pass it on!

Other people are reading…

About the Swift Knowledge Base

This is part of the Swift Knowledge Base, a free, searchable collection of solutions for common iOS questions.

Become a Swift guru

I wrote a book called Pro Swift that's dedicated to helping you master the Swift language, and it includes seven hours of video demonstrating each technique!

Click here to visit the Hacking with Swift store >>