的所有值我有一個字典,這種結構更新詞典
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