Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing Specific Object In Array Based On Property?

I have an array of drink toppings and want to remove the ones that aren't relevant to the drink, this is the code I have, but I can't figure out how to remove the topping from the array if it isn't within the criteria.

I can only remove at index path and this can change if we added more toppings etc so didn't seem accurate?

for toppings in self.toppings {
    if self.selectedDrink.name == "Tea" {
        if toppings.limit == "C" {
            self.toppings.remove(at: toppings)
        }
    }
}

Essentially if the user selected Tea it looks for toppings limited for coffee and then I need to remove those ones that respond to the "C" property, but I can't see how?

Thanks for the help!

like image 572
jwarris91 Avatar asked Jun 18 '17 11:06

jwarris91


1 Answers

You can do in-place removal with a for loop, but it would be tricky, because you would need to iterate back to avoid disturbing indexes.

A simpler approach is to filter the array, and assign it back to the toppings property, like this:

toppings = toppings.filter {$0.limit != "C"}
like image 116
Sergey Kalinichenko Avatar answered Oct 30 '22 10:10

Sergey Kalinichenko