Bi-directional dictionary in objective-c

醉酒当歌 提交于 2020-01-06 06:37:19

问题


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?

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.

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

Thanks.


回答1:


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"]



回答2:


if each Key has a unique(!!!) value you can add a Category to NSDictionary with

-(NSString*)keyForValue:(id)value{
    NSArray* allKeys = [self allKeysForObject:value];
    return [allKeys count] > 0 ? [allKeys objectAtIndex:0] : nil;
}


来源:https://stackoverflow.com/questions/48821215/bi-directional-dictionary-in-objective-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!