gpt4 book ai didi

swift - 以数组为值过滤字典

转载 作者:搜寻专家 更新时间:2023-10-30 22:09:32 25 4
gpt4 key购买 nike

我有字典 [String: [Object]]。每个对象都有.name

是否可以在字典上使用 .filter 来返回仅包含过滤值的键的字典?

最佳答案

如果我理解你的问题,你想要 [String: [Object]] 字典的,其中每个 Object 都有一个 name 属性,并且此属性具有给定值。

struct Obj {
let name: String
}

let o1 = Obj(name: "one")
let o2 = Obj(name: "two")
let o3 = Obj(name: "three")

let dict = ["a": [o1, o2], "b": [o3]]

现在假设您想要对象名称为“two”的字典键:

带有过滤器的解决方案

let filteredKeys = dict.filter { (key, value) in value.contains({ $0.name == "two" }) }.map { $0.0 }

print(filteredKeys)

使用 flatMapcontains 的解决方案

let filteredKeys = dict.flatMap { (str, arr) -> String? in
if arr.contains({ $0.name == "two" }) {
return str
}
return nil
}

print(filteredKeys)

带循环的解决方案

var filteredKeys = [String]()

for (key, value) in dict {
if value.contains({ $0.name == "two" }) {
filteredKeys.append(key)
}
}

print(filteredKeys)

关于swift - 以数组为值过滤字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38438137/

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