【问题标题】:Remove dictionary from array where value is empty string (Using Higher Order Functions)从值为空字符串的数组中删除字典(使用高阶函数)
【发布时间】:2017-04-17 11:34:08
【问题描述】:

我有一个字典数组

    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)实现这一点

【问题讨论】:

    标签: arrays swift dictionary higher-order-functions


    【解决方案1】:

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

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

    或者,

    let filteredDetails = details
        .filter { !$0.values.contains(where: { $0.isEmpty }) }
    

    另一方面:看到您使用带有一些看似“静态”键的字典数组,我建议您考虑使用更合适的数据结构,例如自定义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 { !$0.name.isEmpty && !$0.age.isEmpty }
    print(filteredDetails)
    /* [Detail(name: "a", age: "1"),
        Detail(name: "b", age: "2")] */
    

    【讨论】:

      【解决方案2】:

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

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

      谢谢

      【讨论】:

      • 抱歉,匆忙打错字了。如果对您有帮助,请采纳答案。
      • 我认为您正在寻找的逻辑是let arrFilteredDetails = details.filter { !($0["name"] == "" || $0["age"] == "") }
      【解决方案3】:

      你可以试试:

      let filtered = details.filter { !$0.values.contains { $0.isEmpty }}
      

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-05-08
        • 2018-04-12
        • 1970-01-01
        • 2019-05-21
        • 1970-01-01
        • 1970-01-01
        • 2016-05-30
        相关资源
        最近更新 更多