Search code examples
iosswift3nspredicate

How to filter an array using NSPredicate in swift 3


I have an arraycontaining several dictionaries.

{
   DisplayName?:"Name of the employee"
   Age:28
   Department:"Dept 2"
}

I just converted my objective-c code into swift and trying to filter like this.

let exists = NSPredicate(format: "DisplayName2 CONTAINS[cd] \(searchText!)")
    let aList: Array<Any> = arrayDirectory.filter { exists.evaluate(with: $0) }
    if(aList.count>0)
    {
        arrayDirectory=aList
        facesCarousel.reloadData()
    }

But I am always getting the aList count as 0. It seems like not filtering my array. How can I write proper NSPredicatein swift 3 and filter my array using it.


Solution

  • The native Swift equivalent to the ObjC code is

    let filteredArray = arrayDirectory.filter { ($0["displayName2"] as! String).range(of: searchText!, options: [.diacriticInsensitive, .caseInsensitive]) != nil }
    

    assuming arrayDirectory is a native Swift Array. It considers also the case insensitive and diacritic insensitive parameters.