2017-03-06 79 views
2

的所有值我有一个字典,这种结构更新词典

var profiles: Dictionary<String, Bool> = ["open": true, "encrypted": false, "sound":true, "picture":false] 

我想创建所有的字典值重置为true的功能。是否有一个简短的方法来做到这一点,或者我应该循环并逐个更改值?

+0

您不使用任何结构的原因? – BallpointBen

回答

3

轻松一内衬为您提供:

profiles.keys.forEach { profiles[$0] = true } 

这遍历字典中的每一个键,并设置为关键true值。 $0代表关闭(关键)forEach中的第一个参数。我没有看到将所有值更改为单个值而不循环的方法。

+1

或'for profiles.keys {profiles [key] = false}中的键' - 只是稍长一些,但更易于阅读:) –

+0

@MartinR它也避免了创建闭包,这可能会有性能优势 – Alnitak

1
dictionary.forEach({ (key, value) -> Void in 
    dictionary[key] = true     
}) 

这里的另一种方法。在这种情况下,只有更新必须更新这些字典项..

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

不会产生这种情况警告未使用的'value'参数? – Alnitak

+2

这里你不需要使用'enumerated()'。也不需要'filter'和'forEach'--一个简单的'for in'循环可以一次完成两个操作,''用于'value {profiles [key] = true}配置文件中的(key,value)'。 – Hamish

+0

你是对的@Hamish。我的第二个片段,它只是一个“练习”:)它更可取的解决方案,更好;) – Adolfo

0

有很多方法对皮肤这个特别的猫......

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