Search code examples
swiftswift2ios9

Swift: Removing limited number of Objects from an Array without using index


I have the following array:

let chPizza = ["type": "deep", "Style" : "Chicago", "Size" : 12]
let nyPizza = ["type": "thin", "Style" : "New York", "Size" : 14]
let caPizza = ["type": "thai", "Style" : "California", "Size" : 12]
let gkPizza = ["type": "thick", "Style" : "Greek", "Size" : 16]


var pizzas = [chPizza, chPizza, gkPizza, nyPizza, caPizza, chPizza, chPizza, gkPizza, caPizza, chPizza]

How can I remove the first 3 elements of chPizza? Do I have to use the old for-loop, or is there a high-order function that I can use?


Solution

  • Let's create our own higher-order method:

    extension Array where Element:Equatable {
        mutating func removeObject(obj:Element) {
            if let ix = self.indexOf(obj) {
                self.removeAtIndex(ix)
            }
        }
    }
    

    Okay, here we go; it's now a one-liner (but observe that we must cast to NSDictionary because Swift dictionaries are not Equatable so you can't find one in an array):

    let chPizza = ["type": "deep", "Style" : "Chicago", "Size" : 12]
    let nyPizza = ["type": "thin", "Style" : "New York", "Size" : 14]
    let caPizza = ["type": "thai", "Style" : "California", "Size" : 12]
    let gkPizza = ["type": "thick", "Style" : "Greek", "Size" : 16]
    
    var pizzas : [NSDictionary] = [chPizza, chPizza, gkPizza, nyPizza, caPizza, chPizza, chPizza, gkPizza, caPizza, chPizza]
    
    (0..<3).forEach {_ in pizzas.removeObject(chPizza)}
    

    Note that this is inefficient! But we can afford that if the array is small and the number of times we remove is small.