2016-02-28 69 views
-1

我有一个元素的数组与索引数组从第一阵列删除:在水果项的数组创建所选项目的数组

如果
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

减小的数组不是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"}] 
+0

对不起,马特,我不够具体。在fruitArray中,我只想删除例如第1项(苹果) – kangarooChris

+0

嗯,你是对的,它的工作原理,我喜欢每个更好,因为我可以比地图更好地理解它 – kangarooChris