如何交换NSMutableDictionary键和值到位? [英] How to swap `NSMutableDictionary` key and values in place?
本文介绍了如何交换NSMutableDictionary键和值到位?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个NSMutableDictionary
,我想交换值&键.即,在交换值之后,值变成了键,而与其交换的键变成了值.所有键和值都是唯一的.由于尺寸非常大,因此需要就地解决方案.另外,键和值是NSString
对象
I have a NSMutableDictionary
and I want to swap values & keys. i.e, after swapping values becomes keys and its corresponding keys with become values All keys and values are unique. Looking for an in place solution because size is very big . Also, the keys and values are NSString
objects
推荐答案
NSMutableDictionary *d = [NSMutableDictionary dictionaryWithDictionary:@{
@"key1" : @"value1",
@"key2" : @"value2"}];
for (NSString *key in [d allKeys]) {
d[d[key]] = key;
[d removeObjectForKey:key];
}
NSLog(@"%@", d); // => { value1 : key1,
// value2 : key2 }
假设
- 唯一值(因为它们将成为键)
- 值符合
NSCopying
(与上面相同) - 没有值等于任何键(否则冲突名称将在此过程中丢失)
- unique values (as they will become keys)
- values conform to
NSCopying
(same as above) - no value is equal to any key (otherwise colliding names will be lost in the process)
Assumptions
这篇关于如何交换NSMutableDictionary键和值到位?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文