使用路径突变嵌套字典



我有一个[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];
}
}

动态执行此操作的最佳方法是在Swift中继续使用NSMutableDictionary。Swift字典似乎没有一个好的方法来做到这一点,除了创建结构/类来表示实际的键,而不是动态地这样做。谢谢matt和Sulthan。

最新更新