Filtering an Array

I'm trying to filter an array containing Recipes that have a property called title of type String that is required.

These are the variables used in the line of code:

@State private var searchingFor = ""
@State private var filteredRecipes = [Recipe]()

This is the line of code giving me the error:

filteredRecipes=filteredRecipes.filter{$0.title.contains(searchingFor)}

The error: "Value of optional type 'String?' must be unwrapped to refer to member 'contains' of wrapped base type 'String'"

Any ideas on how I need to rewrite that line of code so that I don't get that error? ie. how do I unwrap 'String?'

Accepted Reply

When you post a question, please provide complete information (it may appear in another post, but we usually don't know).

How is Recipe defined ? Is title an optional String?

If so, you get the error.

To correct:

filteredRecipes = filteredRecipes.filter{($0.title ?? "").contains(searchingFor)}

Or is searchingFor an optional ? It may be if result or a query for instance.

If so, change to:

filteredRecipes = filteredRecipes.filter{$0.title.contains(searchingFor ?? "")}
  • At the end of the first paragraph it says the title is a string that is not optional.

Add a Comment

Replies

When you post a question, please provide complete information (it may appear in another post, but we usually don't know).

How is Recipe defined ? Is title an optional String?

If so, you get the error.

To correct:

filteredRecipes = filteredRecipes.filter{($0.title ?? "").contains(searchingFor)}

Or is searchingFor an optional ? It may be if result or a query for instance.

If so, change to:

filteredRecipes = filteredRecipes.filter{$0.title.contains(searchingFor ?? "")}
  • At the end of the first paragraph it says the title is a string that is not optional.

Add a Comment

it says the title is a string that is not optional

But the compiler disagrees, as the error message basically says the title property is an Optional<String>. Can you show the definition of the Recipe type?

just force unwrap your title since it is required for Recipe it should be safe

filteredRecipes=filteredRecipes.filter{$0.title!.contains(searchingFor)}

but it would be better if you define the property title as not optional instead.