unknown
unknown

Reputation: 978

remove items at multiple indexes in an array

code below removes only the first item in the array with color property set to "black"

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)

i want delete all the items in the array with the color property set to "black"

Upvotes: 0

Views: 73

Answers (1)

Shehata Gamal
Shehata Gamal

Reputation: 100503

You can try

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

Upvotes: 2

Related Questions