删除基于属性的数组中的特定对象? [英] Removing Specific Object In Array Based On Property?
问题描述
我有一系列的饮料配料,并且想要删除与饮料无关的配料,这是我的代码,但是我不知道如何从数组中删除配料不在标准之内.
我只能在索引路径处删除,并且如果我们添加更多的浇头等,这可能会改变,所以看起来不太准确?
for toppings in self.toppings {
if self.selectedDrink.name == "Tea" {
if toppings.limit == "C" {
self.toppings.remove(at: toppings)
}
}
}
基本上,如果用户选择茶",它会寻找咖啡的浇头,然后我需要删除那些响应"C"属性的浇头,但我看不到如何?
感谢您的帮助!
您可以使用for
循环进行就地删除,但这会很棘手,因为您需要迭代回去以避免干扰索引. /p>
一种更简单的方法是过滤数组,并将其分配回toppings
属性,如下所示:
toppings = toppings.filter {$0.limit != "C"}
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"}
这篇关于删除基于属性的数组中的特定对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!