[英]How to filter an array of structs with value of other array in 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. 我已经搜索了这个问题,但是没有找到使用最新版本的Xcode和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 }}
I use the last array in the tableView
. 我使用
tableView
的最后一个数组。 If they want to see all meals, the filteredArray
is the same as the baseArray
. 如果他们想查看所有餐点,则
filteredArray
与baseArray
相同。
My question: how can I get the filteredArray
that it has all favorite meals (so where Meal.title == Favorite.name
). 我的问题:我如何才能获得
filteredArray
,它拥有所有喜欢的食物(所以这里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!! 上周我尝试了很多选择,但没有一个奏效。.希望您能帮帮我!
This does what you want: 这就是您想要的:
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) }
This is the solution for you if I correctly understand your question. 如果我正确理解您的问题,这就是您的解决方案。
struct Meal {
let name: String
}
struct Favorite {
let name: String
}
let baseArray = [Meal(name: "Meal1"), Meal(name: "Meal2"), Meal(name: "Meal3")]
let favoritesArray = [Favorite(name: "Meal1")]
let searchText = "Meal3"
let filteredArray = baseArray.filter { $0.name == searchText }
print(filteredArray)
// [Meal(name: "Meal3")]
let combinedArray = baseArray.reduce(filteredArray) { array, element in
// First condition check if the current meal (element) in contained in the favorites
// Second checks if the favorite meal isn't already in the filteder array
if favoritesArray.contains(where: { $0.name == element.name }) &&
!filteredArray.contains(where: { $0.name == element.name }) {
return array + [element]
}
return array
}
print(combinedArray)
// [Meal(name: "Meal3"), Meal(name: "Meal1")]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.