不确定是否需要减少,排序,过滤或使用较新的独特方法。我什至尝试了Equatable解决方案。
我需要自动识别具有匹配值的键,并仅采用那些键并将其放入新的字典或数组中。
var userDB: [String:Any] = ["userID1":"gameIDa", "userID2":"gameIDa", "userID3":"gameIDc", "userID4":"gameIDd", "userID5":"gameIDe"]
如您所见,只有这两个ID具有相同的gameIDa
值。我需要此结果的输出。
// [userID1, userID2]
谢谢
答案 0 :(得分:2)
您可以使用Dictionary(grouping:by:)轻松实现此目的,然后将其简化为仅包含具有多个值的条目的字典。
var userDB: [String: String] = ["userID1":"gameIDa", "userID2":"gameIDb", "userID3":"gameIDc", "userID4":"gameIDa", "userID5":"gameIDe"]
let dict = Dictionary(grouping: userDB.keys) { userDB[$0] ?? "" }.reduce(into: [String:[String]](), { (result, element) in
if element.value.count > 1 {
result[element.key] = element.value
}
})
dict
[“ gameIDa”:[“ userID1”,“ userID4”]]
答案 1 :(得分:1)
首先,为了能够比较值,Dictionary
Value
类型必须是Equatable
类型。完成此操作后,您可以轻松过滤保存查询值的键:
extension Dictionary where Value: Equatable {
func keysWithCommonValues() -> [Key] {
// go over all keys and keep ones for which the dictionary has one another key with the same value
return keys.filter { key in contains { $0.key != key && $0.value == self[key] } }
}
}
// userDB is not inferred as [String:String]
var userDB = ["userID1":"gameIDa", "userID2":"gameIDa", "userID3":"gameIDc", "userID4":"gameIDd", "userID5":"gameIDe"]
print(userDB.keysWithCommonValues()) // ["userID1", "userID2"]