我有字典[String: [Object]]
。每个对象都有.name
是否可以在字典上使用.filter
返回仅包含过滤值的字典的字典?
答案 0 :(得分:6)
如果我理解了您的问题,您需要[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”的字典键:
filter
let filteredKeys = dict.filter { (key, value) in value.contains({ $0.name == "two" }) }.map { $0.0 }
print(filteredKeys)
flatMap
和contains
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)
答案 1 :(得分:2)
是的,但是因为你得到一个带有数组值的词典:
dictionary.flatMap({ $0.1.filter({ $0.name == "NameToBeEqual"}) })