Objective-C 中的双向字典 [英] Bi-directional dictionary in objective-c

查看:62
本文介绍了Objective-C 中的双向字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一对一映射的键值对.对于每个键,我都有独特的价值.那么我可以制作一个双向字典或类似的东西,它可以从键中给我值,反之亦然?

Suppose I have key-value pairs having one to one mapping. For each key I have unique value. Then can I make a bi-directional dictionary or something similar to it which can give me value from key and vice versa?

附言- 我知道我可以使用 [NSDictionary allKeysForObject: (nonnull id)] 它返回具有该值的所有键的 NSArray.

P.S. - I know that I can use [NSDictionary allKeysForObject: (nonnull id)] which returns an NSArray of all keys having that value.

我只是想知道是否有双向字典之类的东西,然后它会很有用.

I was just wondering if there is something like bi-directional dictionary then it will be useful.

如果有类似的东西,那么也请为 swift 提供解决方案.

If there is something like that then please provide solution for swift also.

谢谢.

推荐答案

您可以扩展 Dictionary 将其 Value 约束为 Equatable 并提供您的自己的 subscript 返回 value 的第一个键:

You can extend Dictionary constraining its Value to Equatable and provide your own subscript to return the first key for value:

Xcode 11 • Swift 5.1

extension Dictionary where Value: Equatable {
    subscript(firstKeyFor value: Value) -> Key?  { first { $0.value == value }?.key }
    func allKeys(for value: Value) -> [Key] { compactMap { $0.value == value ? $0.key : nil } }
}

<小时>

let dict = ["One": 1, "Two": 2, "Three": 3, "Um": 1, "Dois": 2, "Tres": 3]

if let key =  dict[firstKeyFor: 1] {
    print(key)   // "One"
}

let allKeys = dict.allKeys(for: 2)  // ["Dois", "Two"]

这篇关于Objective-C 中的双向字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆