gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 09:32:14 26 4
gpt4 key购买 nike

我有一个字典数组

    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)实现此目的

最佳答案

根据您的 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")] */

关于arrays - 从值为空字符串的数组中删除字典(使用高阶函数),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43450670/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com