从值为空字符串的数组中删除字典(使用高阶函数)

Remove dictionary from array where value is empty string (Using Higher Order Functions)

我有一个字典数组

    var details:[[String:String]] = [["name":"a","age":"1"],["name":"b","age":"2"],["name":"c","age":""]]
    print(details)//[["name": "a", "age": "1"], ["name": "b", "age": "2"], ["name": "c", "age": ""]]

现在我想从值为空字符串的数组中删除字典。我已经通过嵌套的 for 循环实现了这一点。

    for (index,detail) in details.enumerated()
    {
       for (key, value) in detail
       {
        if value == ""
        {
            details.remove(at: index)
        }
       }
    }
    print(details)//[["name": "a", "age": "1"], ["name": "b", "age": "2"]]

如何使用高阶函数(Map、filter、reduce 和 flatMap)实现此目的

您可以使用如下数组的过滤方式

let arrFilteredDetails = details.filter { ([=10=]["name"] != "" || [=10=]["age"] != "")}

谢谢

你可以试试:

let filtered = details.filter { ![=10=].values.contains { [=10=].isEmpty }}

这也独立于内部字典结构(如键名)

根据您的 for 循环,如果其中任何键值对包含空 String"",您似乎想从 details 中删除字典作为一个值。为此,您可以例如将 filter 应用于 details,并作为 filter 的谓词,检查每个字典的 values 属性 是否不存在 ""(/不存在空 String)。例如

var details: [[String: String]] = [
    ["name": "a", "age": "1"],
    ["name": "b", "age": "2"],
    ["name": "c", "age": ""]
]

let filteredDetails = details.filter { ![=10=].values.contains("") }
print(filteredDetails)
/* [["name": "a", "age": "1"], 
     "name": "b", "age": "2"]] */

或者,

let filteredDetails = details
    .filter { ![=11=].values.contains(where: { [=11=].isEmpty }) }

另一个注意事项:看到您使用带有一些看似 "static" 键的字典数组,我建议您考虑使用更合适的数据结构,例如自定义 Struct。例如:

struct Detail {
    let name: String
    let age: String
}

var details: [Detail] = [
    Detail(name: "a", age: "1"),
    Detail(name: "b", age: "2"),
    Detail(name: "c", age: "")
]

let filteredDetails = details.filter { ![=12=].name.isEmpty && ![=12=].age.isEmpty }
print(filteredDetails)
/* [Detail(name: "a", age: "1"),
    Detail(name: "b", age: "2")] */