我已经搜索过这个问题,但是我找不到任何使用最新版Xcode和Swift的解决方案。我使用三个数组:
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
相同。
我的问题:我怎样才能得到filteredArray
所有喜欢的饭菜(Meal.title == Favorite.name
)。我如何组合三个阵列?
我在上周尝试了很多选项,但没有一个可行。我希望你能帮帮我!!
答案 0 :(得分:2)
这样做你想要的:
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) }
答案 1 :(得分:0)
如果我正确理解您的问题,这是您的解决方案。
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")]