的所有值我有一个字典,这种结构更新词典
var profiles: Dictionary<String, Bool> = ["open": true, "encrypted": false, "sound":true, "picture":false]
我想创建所有的字典值重置为true的功能。是否有一个简短的方法来做到这一点,或者我应该循环并逐个更改值?
的所有值我有一个字典,这种结构更新词典
var profiles: Dictionary<String, Bool> = ["open": true, "encrypted": false, "sound":true, "picture":false]
我想创建所有的字典值重置为true的功能。是否有一个简短的方法来做到这一点,或者我应该循环并逐个更改值?
轻松一内衬为您提供:
profiles.keys.forEach { profiles[$0] = true }
这遍历字典中的每一个键,并设置为关键true
值。 $0
代表关闭(关键)forEach
中的第一个参数。我没有看到将所有值更改为单个值而不循环的方法。
或'for profiles.keys {profiles [key] = false}中的键' - 只是稍长一些,但更易于阅读:) –
@MartinR它也避免了创建闭包,这可能会有性能优势 – Alnitak
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 }
您不使用任何结构的原因? – BallpointBen