0

这有点难以解释,但我会尽力而为。我正在尝试正确更新另一个字典中的字典。以下代码几乎可以满足我的需要。

var dictionary = Dictionary<String, [Int : Int]>()

func handleStatsValue(tag: Int ) {
        let currentValue: Int = dictionary["Score"]?[tag] ?? 0

        dictionary["Score"] = [
            tag : currentValue + 1
        ]
 }

tag但是,当值更改(例如,从 1 到 2)时,字典似乎会被覆盖。我需要Dictionary在里面有多个字典。任何提示或建议都深表感谢。

编辑:我正在尝试将多个字典嵌套在字典中。似乎每当tag更改值时,字典都会被覆盖。

4

2 回答 2

2

一种写法是:

func handleStatsValue(tag: Int) {
    dictionary["Score", default: [:]][tag, default: 0] += 1
}

或者,没有写[_:default:]

func handleStatsValue(tag: Int) {
    var scoreDictionary = dictionary["Score"] ?? [:]
    scoreDictionary[tag] = (scoreDictionary[tag] ?? 0) + 1
    dictionary["Score"] = scoreDictionary
}

但是,使用嵌套字典来保存数据并不是一个好主意。改用自定义struct并尽量避免使用标签:

struct DataModel {
    var score: [Int: Int] = [:]
}
于 2018-12-22T20:45:47.657 回答
0

我认为您需要这样的东西来增加现有标签的价值或添加新标签(如果它不存在)

func handleStatsValue(tag: Int ) {
    if var innerDict = dictionary["Score"] {
        if let value = innerDict[tag] {
            innerDict[tag] = value + 1
        } else {
            innerDict[tag] = 1
        }
        dictionary["Score"] = innerDict
    }    
}

尽管硬编码键“Score”的代码看起来有点奇怪,但最好有多个简单的字典,比如

var score: [Int, Int]()

或者如果你喜欢

var score = Dictionary<Int, Int>()
于 2018-12-22T20:43:49.687 回答