1

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?

3
  • What do you mean by "remove the first 3 elements without knowing the index"? What's your expected result? Commented Mar 4, 2016 at 4:13
  • 1
    do you mean remove the first three instances of "chPizza" in the array "pizzas" Commented Mar 4, 2016 at 4:32
  • Yes, remove first three instances of "chPizza". Commented Mar 4, 2016 at 4:33

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

you're just killing it today!
It's not my fault. You're the one who keeps asking the fun questions!
This gives me an error: Type ["String":"String"] does not conform to protocol 'Equatable'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.