Skip to content

Instantly share code, notes, and snippets.

@pedromancheno
Last active December 25, 2015 15:09
Show Gist options
  • Save pedromancheno/6995661 to your computer and use it in GitHub Desktop.
Save pedromancheno/6995661 to your computer and use it in GitHub Desktop.
Categories for NSDictionary and NSArray for swapping the keys of a dictionary.
@interface NSDictionary (Swapping)
- (NSDictionary *)dictionaryBySwappingKey:(id)oldKey withKey:(id)newKey;
@end
@implementation NSDictionary (Swapping)
- (NSDictionary *)dictionaryBySwappingKey:(id)oldKey withKey:(id)newKey
{
NSMutableDictionary *mutableDictionary = [NSMutableDictionary dictionaryWithCapacity:self.count];
[self enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
BOOL shouldSwapKey = [key isEqual:oldKey];
if ([obj isKindOfClass:[NSDictionary class]]) {
NSDictionary *newDict = [obj dictionaryBySwappingKey:oldKey withKey:newKey];
id aKey = shouldSwapKey ? newKey : key;
mutableDictionary[aKey] = newDict;
} else if ([obj isKindOfClass:[NSArray class]]) {
NSArray *newArray = [obj arrayBySwappingKey:oldKey withKey:newKey];
id aKey = shouldSwapKey ? newKey : key;
mutableDictionary[aKey] = newArray;
} else {
id aKey = shouldSwapKey ? newKey : key;
mutableDictionary[aKey] = obj;
}
}];
return [NSDictionary dictionaryWithDictionary:mutableDictionary];
}
@end
@interface NSArray (Swapping)
- (NSArray *)arrayBySwappingKey:(id)oldKey withKey:(id)newKey;
@end
@implementation NSArray (Swapping)
- (NSArray *)arrayBySwappingKey:(id)oldKey withKey:(id)newKey
{
NSMutableArray *mutableArray = [NSMutableArray arrayWithCapacity:self.count];
[self enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
if ([obj isKindOfClass:[NSDictionary class]]) {
NSDictionary *newDict = [obj dictionaryBySwappingKey:oldKey withKey:newKey];
mutableArray[idx] = newDict;
} else if ([obj isKindOfClass:[NSArray class]]) {
NSArray *newArray = [obj arrayBySwappingKey:oldKey withKey:newKey];
mutableArray[idx] = newArray;
} else {
mutableArray[idx] = obj;
}
}];
return [NSArray arrayWithArray:mutableArray];
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment