Dynamically Filtering a FetchRequest

I am trying to implement a search bar in my recipe storage app. I got recommended using the .filter function that I didn’t know could be used on FetchedResults. So I did and now I’m getting errors, but not ones saying that it isn’t in the scope so I believe this is possible, just now sure how.

The ForEach loop containing the filter: •ForEach(recipes.filter({$0.title.contains(searchingFor)})) { recipe in

Note: Recipes is just a FetchedResults type and searchingFor is just a string that comes from the search bar.

The errors:

•Value of optional type 'String?' must be unwrapped to refer to member 'contains' of wrapped base type 'String'

•Chain the optional using '?' to access member 'contains' only for non-'nil' base values

•Force-unwrap using '!' to abort execution if the optional value contains 'nil'

Any help is greatly appreciated.

hi,

since I am the one who recommended this, I feel it's probably my job to clean this up.

bottom line: I forgot you were working with string attributes in Core Data and they are optional.

option 1: just force-unwrap the title. use this (assuming you always assign a title to a Recipe):

ForEach(recipes.filter({$0.title!.contains(searchingFor)})) { recipe in ...

option 2: If you don't like force-unwrapping, then do this.

first, add an extension to the Recipe class to massage the title a little bit:

extension Recipe {
  var niceTitle: String { title ?? "" }
}

and then rewrite you ForEach construct as

ForEach(recipes.filter({$0.niceTitle.contains(searchingFor)})) { recipe in ...

hope that helps,

DMG

Dynamically Filtering a FetchRequest
 
 
Q