swift - 使用路径改变嵌套字典
问题描述
我有一本字典,[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];
}
}
解决方案
动态执行此操作的最佳方法是继续NSMutableDictionary
在 Swift 中使用。除了创建结构/类来表示实际的键,而不是动态地执行它之外,似乎没有使用 Swift 字典执行此操作的好方法。谢谢马特和苏尔坦。
推荐阅读
- react-native-android - 反应本机按钮中的阴影
- scala - 从 spark 写入 hadoop 的最佳实践
- bash - 在bash中将前100k文件夹从一个目录复制到另一个目录的最快方法是什么
- apache - mod_brotli 和 apache 2.4.33 的编译问题
- android - ndk 套接字在 snapdragon 835 上不起作用
- maven - 我在 Android Studio 中出现 gradle 同步错误,“找不到参数 [com.github.dcendents:android-maven-gradle-plugin:2.0] 的方法 calsspath()”
- c# - 通过 nuget.exe 获取所有已安装的 nuget 依赖项
- java - 使用 Tomcat 8 将外部日志配置的位置指定到特定的 webapps
- mysql - MariaDB 未启动:“插件 'FEEDBACK' 已禁用。”
- c# - 架构层图验证在 .Net 核心中不起作用