从Fruit项目数组中的选定项目创建数组

时间:2016-02-28 21:36:51

标签: arrays swift

我有一个带有项目的数组和一个带有要从第一个数组中删除的索引的数组:

var array = ["a", "b", "c", "d", "e", "f", "g", "h", "i"]    
let indicesToDelete = [4, 8]

let reducedArray = indicesToDelete.reverse().map { array.removeAtIndex($0) }
reducedArray  // prints ["i","e"]

如果我的数组看起来像这样:

class Fruit{
let colour: String
let type: String
init(colour:String, type: String){
    self.colour = colour
    self.type = type
    }
}

var arrayFruit = [Fruit(colour: "red", type: "Apple" ),Fruit(colour: "green", type: "Pear"), Fruit(colour: "yellow", type: "Banana"),Fruit(colour: "orange", type: "Orange")]
let indicesToDelete = [2,3]

如果我只是使用上面的代码,我会收到错误。

let reducedArray = indicesToDelete.reverse().map { arrayFruit.removeAtIndex($0) }//////    error here

我的问题是fruitArray是由对象组成的,我不知道如何调整上面的代码。

1 个答案:

答案 0 :(得分:1)

简化数组不是map的结果,而是原始数组,即arrayFruit。我建议不要使用mapforEach,并将其写成:

class Fruit{
    let colour: String
    let type: String
    init(colour:String, type: String){
        self.colour = colour
        self.type = type
    }
}

var arrayFruit = [Fruit(colour: "red", type: "Apple" ),Fruit(colour: "green", type: "Pear"), Fruit(colour: "yellow", type: "Banana"),Fruit(colour: "orange", type: "Orange")]
let indicesToDelete = [2,3]

indicesToDelete.sort(>).forEach { arrayFruit.removeAtIndex($0) }
arrayFruit // [{colour "red", type "Apple"}, {colour "green", type "Pear"}]