Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Swift 更新字典的所有值_Swift_Dictionary - Fatal编程技术网

Swift 更新字典的所有值

Swift 更新字典的所有值,swift,dictionary,Swift,Dictionary,我有一本这种结构的词典 var profiles: Dictionary<String, Bool> = ["open": true, "encrypted": false, "sound":true, "picture":false] var配置文件:Dictionary=[“打开”:真,“加密”:假,“声音”:真,“图片”:假] 我想创建一个函数,将所有字典值重置为true。有没有一个简单的方法可以做到这一点,或者我应该循环使用它并逐个更改值?简单一行: profiles.k

我有一本这种结构的词典

var profiles: Dictionary<String, Bool> = ["open": true, "encrypted": false, "sound":true, "picture":false]
var配置文件:Dictionary=[“打开”:真,“加密”:假,“声音”:真,“图片”:假]

我想创建一个函数,将所有字典值重置为true。有没有一个简单的方法可以做到这一点,或者我应该循环使用它并逐个更改值?

简单一行:

profiles.keys.forEach { profiles[$0] = true }
这将遍历字典中的每个键,并将该键的值设置为
true
$0
表示
forEach
闭包(键)中的第一个参数。我不认为有一种方法可以将所有值都更改为一个值而不循环

dictionary.forEach({ (key, value) -> Void in 
    dictionary[key] = true                 
})
这里是另一种方法。在这种情况下,仅更新这些必须更新的词典条目

dictionary.filter({ $0.value == false })
    .forEach({ (key, _) -> Void in 
              dictionary[key] = true               
})

有很多方法可以剥这只猫的皮

profiles.forEach { profiles[$0.0] = true }

或者
用于配置文件中的key.keys{profiles[key]=false}
–只稍微长一点,但更容易阅读:)@MartinR它还避免创建闭包,这可能对性能有好处阅读您的答案,起初我认为对字典进行变异似乎不正确。这是你的好把戏。我只希望有一个简单的变异函数。有什么原因吗?@亲爱的,我们正在循环键,因此没有
$0.key
,但是
$0
$1
。感谢您修复@LinusGeffarth。这不会对未使用的
参数产生警告吗?您不需要在这里使用
枚举()
。此外,不需要
过滤器
forEach
–一个简单的
for in
循环可以一次完成这两项工作–
for(key,value)in profiles where!value{profiles[key]=true}
。你说得对@Hamish。我的第二个片段只是一个“练习”:(最好是一个更可读的解决方案;)该过滤器使该任务过于复杂。这样做的时间复杂性已经超过了一次遍历整个密钥列表。如果您真的只想更新尚未
true
的值,只需使用
forEach
,检查指定键的值是否为false,然后更新它。在4键/值字典中,确定;)@你为什么不使用结构?