swift - 在 NSMutableArray 中搜索

标签 swift search nsmutablearray

我想使用键值对 NSMUtableArray 进行搜索,以捕获洞对象,而不仅仅是值数组,例如我的 NSMUtableArray 返回我

{id : 1, name : x1}
{id : 2, name : x2}
{id : 3, name : x3}
{id : 4, name : y1}
{id : 5, name : y2}

如果我正在搜索 x 我的代码返回我

{x1,x2,x3} 

或者我希望它返回

{id : 1, name : x1}
{id : 2, name : x2}
{id : 3, name : x3}

我的代码是:

 let arrayy = lstResults.value(forKey: "name")
 let searchTest = NSPredicate(format: "SELF BEGINSWITH   [c] %@", searchBar.text!)
 let array = (arrayy as! NSArray).filtered(using: searchTest)
 filteredTableDataName = array as NSArray

请帮助我尝试了很多东西,但没有任何效果。

最佳答案

您可以直接过滤数组,使用相应的键路径而不是谓词中的“SELF”,而不是提取和过滤“name”值:

let array = NSArray(array: [
    ["id": 1, "name": "x1"], ["id": 2, "name": "x2"], ["id": 3, "name": "y3"]])

let predicate = NSPredicate(format: "name BEGINSWITH [c] %@", "x")
let filtered = array.filtered(using: predicate)

print(filtered)

结果:

[{
    id = 1;
    name = x1;
}, {
    id = 2;
    name = x2;
}]

另一种选择是将 NS(Mutable)Array 转换为 Swift 字典数组,并使用 filter() 函数:

if let a = array as? [[String: Any]] {
    let filtered = a.filter {
        ($0["name"] as? String)?
            .range(of: "x", options: [.caseInsensitive, .anchored]) != nil
    }
    print(filtered)
    // [["id": 1, "name": x1], ["name": x2, "id": 2]]
}

关于swift - 在 NSMutableArray 中搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58318682/

相关文章:

php - 清理mysql搜索字符串的功能(主要是删除通配符)?

ios - 如何在 NSMutableArray 中存储 indexPath 时传入节值

ios - 如何在 iphone 的 UITableview 单元格中设置文本位置数组

ios - 正确理解 swift 中的prepareforsegue

ios - 如何快速从 AVCaptureStillImageOutput 创建 CIImage?

swift - macOS NSTabViewController 居中选项卡图标

ios - 如何更新 cocoapods 1.7.x 上的build设置

mysql - 如何使用 codeigniter 在多个表中进行搜索?

c - char数组是否包含字符串?

ios - 如何使图像对应于 NSMutableArray 中的每个对象 - xcode 7.3