使用数组作为值过滤字典

时间:2016-07-18 13:34:58

标签: swift

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

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

2 个答案:

答案 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)

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)

答案 1 :(得分:2)

是的,但是因为你得到一个带有数组值的词典:

dictionary.flatMap({ $0.1.filter({ $0.name == "NameToBeEqual"}) })