Last active
December 25, 2015 15:09
-
-
Save pedromancheno/6995661 to your computer and use it in GitHub Desktop.
Categories for NSDictionary and NSArray for swapping the keys of a dictionary.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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