我有一本字典,[String : Any]
我需要在字典中的未知位置改变一些值。它们由传递给方法的路径列表给出。如果我已经有了钥匙,它看起来像:dic["key1"]["key2"] = ["val":1]
. 实现这一目标的最佳方法是什么?
这段代码旨在改变用户偏好的字典,最初是用 obj-C 编写的,其中字典是通过引用传递的。基本上,这些就像 JSON 节点,因此Any
不是强类型的。
这是我要转换的代码,我没有写:
- (void)setRelativePath:(NSString *)path add:(BOOL)add {
NSMutableArray *pathComponents = [[[self fullPath:path] componentsSeparatedByString:@"."] mutableCopy];
if ([pathComponents count]) {
if ([pathComponents count] > 1) {
NSString *rootKey = pathComponents[0];
[pathComponents removeObjectAtIndex:0];
NSMutableDictionary *rootDictionary = [[self.cacheGetter() dictionaryForKey:rootKey] mutableCopy];
if (!rootDictionary) {
rootDictionary = [NSMutableDictionary new];
}
NSMutableDictionary *dictionary = rootDictionary;
while ([pathComponents count] > 1) {
NSString *nextKey = pathComponents[0];
NSDictionary *current = dictionary[nextKey];
[pathComponents removeObjectAtIndex:0];
NSMutableDictionary *next = current ? [current mutableCopy] : [NSMutableDictionary new];
dictionary[nextKey] = next;
dictionary = next;
}
if (add) {
dictionary[pathComponents[0]] = @(YES);
} else {
[dictionary removeObjectForKey:pathComponents[0]];
}
[self.cacheGetter() setValue:rootDictionary forKey:rootKey];
} else if (add) {
[self.cacheGetter() setBool:YES forKey:path];
} else {
[self.cacheGetter() removeObjectForKey:path];
}
[self.cacheGetter() synchronize];
}
}