How to remove an array of objects from a Swift 2 Array - removeObjectsInArray

removeObjectsInArray Swift Protocol Extension.png

I was working on a game project in Swift and I wanted to remove objects from an Array, only to discover that my goto method from Objective-C’s NSMutableArray (removeObjectsInArray:) didn’t exist.

Removing multiple objects from an Array takes multiple steps – when you iterate over an Array you cannot remove objects. It’s a two step process, you need to discover which objects need to be removed and then you need to iterate through that list and remove each one, one at a time.

The code has changed between Swift 1.2 and Swift 2 – I’ll include both to show the differences.

Swift 1.2 Remove Multiple Objects from an Array

You can start by creating an array of objects – add to the end with append() or insert() at a specific index.

Next you will need to search for something in your Swift Array – for this example you’ll look for words with a specific letter. 

Lastly you’ll need to remove each word that contains the letter one at a time, outside of your first loop.

// Swift 1.2
var wordArray = ["Apple", "Carrot", "Peanut Butter"]
wordArray.append("Hummus")
wordArray.insert("Greek Salad", atIndex: 0)

// Find the objects to remove
var wordsToDelete: [String] = [String]()
for word in wordArray {
    if contains(word.lowercaseString, "p") {
        wordsToDelete.append(word)
    }
}

// Find the index and remove each object
for word in wordsToDelete {
    if let index = find(wordArray, word) {
        wordArray.removeAtIndex(index)
    }
} 

Swift 2 Remove Multiple Objects from an Array

Swift 2 changes the contains() function to a contains() method using Protocol Extensions and since we’re working with Swift 2 Strings – the character property needs to be used.

The global find() function is now replaced by the new indexOf() method on Array (technically CollectionType).

// Swift 2
var wordArray = ["Apple", "Carrot", "Peanut Butter"]
wordArray.append("Hummus")
wordArray.insert("Greek Salad", atIndex: 0)

// Find the objects to remove
var wordsToDelete: [String] = [String]()
for word in wordArray {
    if word.lowercaseString.characters.contains("p") {
        wordsToDelete.append(word)
    }
}

// Find the index and remove each object
for word in wordsToDelete {
    if let index = wordArray.indexOf(word) {
        wordArray.removeAtIndex(index)
    }
} 

 

Swift 2 Array Protocol Extension removeObjectsInArray

With the basics of removing objects from an Array you can take it a step further to get back to a single line of code to remove objects.

Using an extension in Swift 2 allows you to add functionality that’s missing from the Array type. An Array is a structure, so you’ll have to use the mutating keyword and the Element is the type of object that is in the Array (generics).

Equatable means that the type must support the == (equal to) method, which is required to find an object. String objects are already equatable, so you don't need to do any extra work. If you are storing a custom object you will need to implement your own isEqual method.

// Swift 2 Array Extension
extension Array where Element: Equatable {
    mutating func removeObject(object: Element) {
        if let index = self.indexOf(object) {
            self.removeAtIndex(index)
        }
    }
    
    mutating func removeObjectsInArray(array: [Element]) {
        for object in array {
            self.removeObject(object)
        }
    }
}

With the Array Extension you can simplify your last 4 lines of code into a single line of code to remove an array of objects.

// Swift 2
var wordArray = ["Apple", "Carrot", "Peanut Butter"]
wordArray.append("Hummus")
wordArray.insert("Greek Salad", atIndex: 0)

// Find the objects to remove
var wordsToDelete: [String] = [String]()
for word in wordArray {
    if word.lowercaseString.characters.contains("p") {
        wordsToDelete.append(word)
    }
}

// Remove an array of objects
wordArray.removeObjectsInArray(wordsToDelete)

Free Online Swift App Course

Subscribe and get access to the Free iPhone App Course – you can make your first iPhone app using Swift.