如何在swift 3中使用NSPredicate过滤数组 [英] How to filter an array using NSPredicate in swift 3

查看:54
本文介绍了如何在swift 3中使用NSPredicate过滤数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含多个字典的数组.

I have an arraycontaining several dictionaries.

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

我刚刚将我的 Objective-c 代码转换为 swift 并尝试像这样过滤.

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()
    }

但我总是将 aList 计数为 0.似乎没有过滤我的数组.如何在 swift 3 中编写正确的 NSPredicate 并使用它过滤我的数组.

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.

推荐答案

与 ObjC 代码等效的原生 Swift 是

The native Swift equivalent to the ObjC code is

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

假设 arrayDirectory 是一个原生的 Swift Array.它还考虑了 case insensitivediacritic insensitive 参数.

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

这篇关于如何在swift 3中使用NSPredicate过滤数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆