mkw1975 mkw1975 - 1 year ago 95
Swift Question

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. 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
. If they want to see all meals, the
is the same as the

My question: how can I get the
that it has all favorite meals (so where
Meal.title ==
). 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!!

Answer Source

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 = { $ }

let filteredArray = baseArray.filter { favoriteNames.contains($0.title) }
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download