2017-03-06 65 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 }