如何删除swift 2数组元素不在索引处

时间:2016-10-19 09:11:46

标签: arrays swift2

如何删除swift 2数组元素不在索引处?

protocol Food { //Еда
    var name: String {get}
    func taste() -> String
    var pr: Int {get}
}

protocol Storable: Food {
    var expired: Bool {get}
    var daysToExpire: Int {get}
}

class Apple: Food { //Яблоко
    var name = "Яблоко"
    func taste() -> String {
        return "Сладкое"
    }
    var pr = 0
}

class Grapes: Storable { //виноград
    var name = "Виноград"
    func taste() -> String {
        return "Кислый"
    }
    var pr = 0
    var expired = false
    var daysToExpire = 5
}

class Banana: Storable { //Банан
    var name = "Банан"
    func taste() -> String {
        return "Сладкий"
    }
    var pr = 0
    var expired = false
    var daysToExpire = 9
}


class Potato: Food { //картошка
    var name = "Картошк"
    func taste() -> String {
        return "Сладкая"
    }
    var pr = 1
}

class Bow: Food { //Лук
    var name = "Лук"
    func taste() -> String {
        return "Горький"
    }
    var pr = 1
}

class Carrot: Food { //морковь
    var name = "Морковь"
    func taste() -> String {
        return "Сладкая"
    }
    var pr = 1
}

var apple = Apple()
var grapers = Grapes()
var banana = Banana()
var potato = Potato()
var bow = Bow()
var carrot = Carrot()

var basket: [Food] = [apple, grapers, banana, potato, bow, carrot]

func bite(oneBite: [Food]) {
    for bites in basket {
        print("Кусаем \(bites.name), ооо на вкус \(bites.taste())")
    }
}

bite(basket)

var fridge = [Storable]()//пустой массив типа Storable холодильник

for prod in basket {
    if let storableProduct = prod as? Storable where storableProduct.expired == false {
        fridge.append(storableProduct)
    }
}

var trash = [Storable]() //пустой массив типа Storable мусорка

for i in fridge {
    if i.daysToExpire > 6 {
        fridge.removeAtIndex(i)
    }
}

1 个答案:

答案 0 :(得分:1)

首先请发布代码而不是截图。没有人愿意提供帮助,也愿意重新输入代码进行测试。

循环中的索引变量iStorable对象,而不是Int索引,它正是错误消息所说的内容。

使用enumerate获取索引和对象

for (i, storable) in fridge.enumerate {
   if storable.days ... {
     fridge.removeAtIndex(i)
  }
}

但请注意,如果要从刚刚枚举的对象中删除项目,肯定会遇到下一个问题。