如何快速过滤具有其他数组值的结构数组? [英] How to filter an array of structs with value of other array in swift?
问题描述
我已经搜索了这个问题,但是没有找到使用最新版本的Xcode和Swift的解决方案.我使用三个数组:
I have searched for this issue and I did not find any solution that is working for me using the latest version of Xcode and Swift. I use three arrays:
1. baseArray[Meal]: array filled with every meal. Not locally saved.
2. favoritesArray[Favorite]: with names of all favorite meals, locally saved by the user with NSKeyedArchiver.
3. filteredArray[Meal]: baseArray but filtered for searchterm. In code:
(filteredArray = baseArray.filter { $0.type == searchtext }}
我使用tableView
中的最后一个数组.如果他们想查看所有餐点,则filteredArray
与baseArray
相同.
I use the last array in the tableView
. If they want to see all meals, the filteredArray
is the same as the baseArray
.
我的问题:我怎么能得到所有喜欢的饭菜的filteredArray
(所以Meal.title == Favorite.name
在哪里).如何结合三个阵列?
My question: how can I get the filteredArray
that it has all favorite meals (so where Meal.title == Favorite.name
). How do i combine three arrays?
上周我尝试了很多选择,但没有一个奏效..希望您能帮到我!
I have tried a lot of options in the last week, but none has worked.. I hope You can help me out!!
推荐答案
这就是您想要的:
struct Meal {
let title: String
}
struct Favorite {
let name: String
}
let meal1 = Meal(title: "Soup")
let meal2 = Meal(title: "Stew")
let meal3 = Meal(title: "Pizza")
let favorite1 = Favorite(name: "Stew")
let baseArray = [meal1, meal2, meal3]
let favoritesArray = [favorite1]
let favoriteNames = favoritesArray.map { $0.name }
let filteredArray = baseArray.filter { favoriteNames.contains($0.title) }
这篇关于如何快速过滤具有其他数组值的结构数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!