问题
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