过滤字典数组

时间:2018-07-30 06:08:08

标签: arrays swift

我有一个像这样的字典数组。 我必须创建一个包含所有与搜索键匹配的键或包含“ builder_name”键值

的数组
"data": [
    {
        "Websiteuser": {
            "builder_name": "Mahagun India Pvt Ltd "
        },
        "MessageBoardAppusersAlls": {
            "id": "68",
            "message": "Fairpockets is a concept which has originated to not only provide fair priced properties but also allow only fair or trusted builders to list their properties on our website.",
            "created": "2018-07-23 14:24:52"
        },
        "Appusermessages": {
            "status": "1"
        },
        "Project": {
            "project_name": "Mahagun Mantra II"
        }
    },
    {
        "Websiteuser": {
            "builder_name": "Mahagun India Pvt Ltd "
        },
        "MessageBoardAppusersAlls": {
            "id": "69",
            "message": "In the current market anybody can list or advertise properties at any price which they want. This brings confusion to both buyers and sellers and they are not able to ascertain what price to ask as a seller or what price to pay as a buyer.",
            "created": "2018-07-23 14:25:00"
        },
        "Appusermessages": {
            "status": "1"
        },
        "Project": {
            "project_name": "Mahagun Mantra Villaments"
        }
    }
]

1 个答案:

答案 0 :(得分:0)

挑战在于,密钥builder_name在另一个字典中,存储密钥Websiteuser

不要 predicate filter带有结束符

let query = "India"
let filteredArray = mainArray.filter { (dictionary) -> Bool in
    guard let webSiteUser = dictionary["Websiteuser"] as? [String:String],
        let builderName = webSiteUser["builder_name"] else { return false }
    return builderName.range(of: query, options: .caseInsensitive) != nil
}

CONTAINS[C]等效的是range(of: options: .caseInsensitive) != nil