首页 文章

无法将值添加到字典中

提问于
浏览
0

我有一个字典 - > var dictionary = [String : [String]]() ,我想在字典数组中追加字符串值 . 这就是我的做法

for (key, value) in dictionary {
  dictionary.updateValue(value.append(nameText),forKey: "name")
}

这里, nameText 是一个字符串,我收到一个错误说,

不能对不可变值使用变异成员:'value'是'let'常量 .

我究竟做错了什么?非常感谢帮助 .

4 回答

  • 0

    你的第一个问题是 value 是循环体内的 let 常量 . 您必须将其声明为 var 才能使其变异 .

    您的第二个问题是您尝试使用 value.append(nameText) 作为为密钥设置的值 . 但是, append() 将数组变异,并返回 Void .

    第三,不要使用 updateValue(forKey:) . 真的没有意义 . 请改用下标 .

    var dictionary = [
        "a" : ["a"],
        "b" : ["b", "b"],
        "c" : ["c", "c", "c"],
    ]
    
    let nameText = "foo"
    for (key, var value) in dictionary {
        value.append(nameText)
        dictionary["name"] = value
    }
    

    现在,这会让您的代码进行编译,但是我会在每次迭代时覆盖 "name" 键的值,这意味着只有最后一次迭代的值会持续存在 . 此外,因为 Dictionary 没有定义的顺序,所以此代码具有不确定的行为 . 你究竟想做什么?

  • 0

    试试这个:

    for (key, value) in dictionary {
        dictionary.updateValue(value + [nameText], forKey: key)
    }
    
  • 0

    想想它一秒钟; value.append(nameText)action . 它返回 Void (类型为......什么都没有!) .

    您想要将值更新为 upon which an action has been performed .

    而不是手动制作临时副本,修改它,然后使用它来更新某些键的值,您可以简单地使用下标和扩展:

    你想要的是:

    extension Dictionary
    {
        public subscript(forceUnwrapping key: Key) -> Value
        {
            get
            {
                return self[key]!
            }
    
            set
            {
                self[key] = newValue
            }
        }
    }
    

    因此,对于名为 dictionary 的字典:

    for key in dictionary.keys
    {
        dictionary[forceUnwrapping: key].append(nameText)
    }
    

    具体来说, dictionary[forceUnwrapping: key].append(nameText) .

  • 1
    /* example setup */
    var dictionary: [String: [String]] = ["foo": [], "bar": []]
    let nameText = "foobar"
    
    /* append the value of the 'nameText' immutable to each inner array */
    dictionary.keys.forEach { dictionary[$0]?.append(nameText) }
    
    /* ok! */
    print(dictionary) // ["bar": ["foobar"], "foo": ["foobar"]]
    

    但是,如下面的问答所述

    ...,很好地意识到“就地”变异的开销,特别是如果工作性能紧张的应用程序 . 从上面的链接线程中的答案中得到建议,可以采用另一种更明智,更少复制浪费的方法:

    var dictionary: [String: [String]] = ["foo": [], "bar": []]
    let nameText = "foobar"
    
    dictionary.keys.forEach { 
        var arr = dictionary.removeValue(forKey: $0) ?? []
        arr.append(nameText)
        dictionary[$0] = arr
    }
    
    print(dictionary) // ["bar": ["foobar"], "foo": ["foobar"]]
    

相关问题