删除数组中多个索引处的项目

时间:2019-05-29 17:20:57

标签: swift

下面的代码仅删除颜色属性设置为“黑色”的数组中的第一项

struct car {
    let model: String
    let color: String
}

var myCars :[car] = [
    car(name:"model X", color: "black"),
    car(name:"model Y", color: "blue"),
    car(name:"roadster", color: "red"),
    car(name:"model S", color: "black"),
    car(name:"model 3", color: "black")
]

let delList = myCars.index(where: {$0.color == "black"})
myCars.remove(at: delList)

我要删除颜色属性设置为“黑色”的数组中的所有项目

1 个答案:

答案 0 :(得分:2)

您可以尝试

print("Before: \(myCars)")
myCars.removeAll(where: {$0.color == "black"})
print("After: \(myCars)")