FREE: Follow my new 100 Days of Swift challenge! >>

Remove all instances of an object from an array

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.

Buy Testing Swift Buy Practical iOS 12 Buy Pro Swift Buy Swift Design Patterns Buy Swift Coding Challenges Buy Server-Side Swift (Vapor Edition) Buy Server-Side Swift (Kitura Edition) Buy Hacking with macOS Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with Swift Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Beyond Code

Was this page useful? Let me know!

Click here to visit the Hacking with Swift store >>