我们正在开发一个我们有配方的iOS应用程序。在应用程序的第一页,我们有成分列表。用户选择成分,应用程序应列出您可以使用所选成分制作的食谱。我们认为过滤器是个好主意,我们这样做了。您是否认为有一种方法可以改进以下代码或我们可以为此方案做些什么。
此代码也在最后一行给出错误。
let array = [
["id":"Simple and healty salmon", "Ingr": "Salmon"],//in Simple and healty salmon,there is salmon only as ingridient.When salmon is checked ,Simple and healthy salmon recipe has to come out.
["id":"Boiled Eggs", "Ingr": "Egg"],//other recipies are as follows
["id":"Perfect Basic White Rice", "Ingr": "Rice"],
["id":"Baba Ghanoush", "Ingr": "Eggplant, Onions ,Garlic, Lemon, Parsley"],
["id":"Really Fudgy Brownies", "Ingr": "Butter, Choclate, Vanilla, Flour"],
["id":"Simple Healthy Summer Salad", "Ingr": "Lettuce, Spinach, Cucumbera, Tomato, Olive Oil"],
["id":"Fried Mashed Potato", "Ingr": "Potato, Onion"],
["id":"Gnocci", "Ingr": "Potato, egg, Flavor"],
["id":"Piyaz", "Ingr": "Potato, egg, Flour"],
["id":"Rice Puding", "Ingr": "Rice, Milk,"],
]
// there is an error at var newArray
var newArray = array.filter { $0["Ingr"] == "Rice" }//here only rice is checked.
print(newArray)
答案 0 :(得分:0)
您应该将它们存储为String
,而不是将这些成分存储为逗号分隔Array<String>
。例如,您的Gnocci条目应为:
["id":"Gnocci", "Ingr": ["Potato", "Egg", "Flavor"]]
然后你可以成功过滤。这是一个完整的例子
let array = [
["id":"Simple and healty salmon", "Ingr": ["Salmon", "Egg"]],
["id":"Boiled Eggs", "Ingr": ["Egg"]],
["id":"Perfect Basic White Rice", "Ingr": ["Rice"]]
]
let results = array.filter { recipe in
if let ingredients = recipe["Ingr"] as? Array<String> {
return ingredients.indexOf("Egg") != nil
}
return false
}
结果将只包含原始数组中的前两项