Filtering data within an array swift

546 Views Asked by At

I'm trying to filter data using a UIMenu. The filter is based on an array of tags which each recipe has. Here is my struct which is populated from a firestore database...

struct RecipeData: Codable {
@DocumentID var id: String?
var recipeType: String?
var recipeName: String?
var recipeCategory: String?
var recipeTags: [String]?
}

I have a separate struct to hold the full list of tags...

struct TagData: Codable {
var customTags: [String] 
}

I've got a filter that works, but will only work if the filter matches the array 100%. I need to match any object in the array, not match the whole thing (if that makes sense) and the recipes can have any number of tags in them from the full list of tags...

self.filteredData = self.recipeData.filter({$0.recipeTags! == [action.title]})

Here is a slightly cut down version of the code I'm using to filter data and reload the tableview

var recipeData: [RecipeData] = []
var tagData: [TagData]?

func popupMenu() {
    // create an array to store the actions
    var optionsArray = [UIAction]()
    
    // create the closure
    let optionClosure = {(action: UIAction) in
        self.headerSearchTitle = action.title
        self.filteredData = self.recipeData.filter({$0.recipeTags! == [action.title]})
        self.isSearching = true //this switches the tables data source
        self.tableView.reloadData()
    }

    var tags = tagData![0].customTags
    // loop and populate the actions array
    for tag in tags {
        // create each action and insert the right country as a title
        let action = UIAction(title: tag, state: .off, handler: optionClosure)
                
        // add newly created action to actions array
        optionsArray.append(action)
    }

    // create an options menu
    let optionsMenu = UIMenu(title: "Custom tags", options: .displayInline, children: optionsArray)
}

Any help welcome!

0

There are 0 best solutions below