首页 > 解决方案 > 使用路径改变嵌套字典

问题描述

我有一本字典,[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 中使用。除了创建结构/类来表示实际的键,而不是动态地执行它之外,似乎没有使用 Swift 字典执行此操作的好方法。谢谢马特和苏尔坦。


推荐阅读