Home > Software engineering >  How do I filter by looking through an array but finding the exact match instead of contains?
How do I filter by looking through an array but finding the exact match instead of contains?

Time:11-17

I am using the following code which allows me to create a new array (of structures) based on whether the structure's property contains the keyword. However, I would like to search the properties for an exact match.

filteredArray = totalArray.filter({ $0.property.contains("keyword")})

So for example if I filtered an array of ["Dog", "Dog", "Big Dog", "Small Dog"], the above equation would return all 4 items with the keyword "Dog". But I would like filteredArray to only return the first 2 items.

Thanks in advance for any help.

CodePudding user response:

You'll have to change the parameter of the filter method to compare the strings directly. You should try this way:

var arr = ["Dog", "Dog", "BigDog", "dd", "eeeeee"]
let result = arr.filter { $0 == "Dog" }
print("Original Array : \(arr)")
print("Filtered Array : \(result)")
  • Related