Swift:不使用索引从数组中删除有限数量的对象

时间:2016-03-04 04:04:08

标签: swift swift2 ios9

我有以下数组:

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]

如何删除chPizza的前3个元素?我是否必须使用旧的for-loop,或者是否有可以使用的高阶函数?

1 个答案:

答案 0 :(得分:2)

让我们创建自己的高阶方法:

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

好的,我们走了;它现在是一个单行(但请注意我们必须转换为NSDictionary,因为Swift词典不是Equatable,所以你不能在数组中找到一个):

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)}

请注意,这是低效的!但是我们可以承受,如果阵列很小,我们删除的次数很少。