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!
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"}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With