从数组中删除字符,其中value为空字符串(使用高阶函数)

时间:2017-04-17 11:34:09

标签: arrays swift dictionary 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": ""]]

现在我想从数组中删除字符,其中value为空字符串。我用嵌套的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)实现此目的

3 个答案:

答案 0 :(得分:4)

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

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。 E.g:

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")] */

答案 1 :(得分:3)

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

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

谢谢

答案 2 :(得分:1)

您可以尝试:

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

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