为什么我不能投一个混合类型字典的值并更新值? [英] Why can't I cast a value of a mixed type dictionary and update the value?
问题描述
我正在尝试回答另一个StackOverflow问题,并发现我对Swift的了解不足。
I was attempting to answer another StackOverflow question and found my knowledge of Swift lacking.
以下是演示我遇到的问题的游乐场代码。
Below is playground code that demonstrates the issue I'm having.
import Foundation
// How do I access the value of dictionary and update the value, without replacing it?
// How do I make the inner dictionary mutable?
var sampleDict = [
"dictionary" : [String: String](),
"array" : [String]()
]
(sampleDict["dictionary"] as! [String:String]).updateValue("avalue", forKey: "akey")
// ERROR: Swift.playground:12:27: error: immutable value of type '[String : String]' only has mutating members named 'updateValue'
//(sampleDict["dictionary"] as! [String:String]).updateValue("avalue", forKey: "akey")
(sampleDict["dictionary"] as! [String:String])["akey"] = "avalue"
// ERROR: Swift.playground:14:56: error: cannot assign to the result of this expression
// (sampleDict["dictionary"] as! [String:String])["akey"] = "avalue"
我的问题是
- 我是否访问mixedType字典的值并更新该值,而不替换它?
- 如何使内部字典变得可变?
- 是这是不可能的?
推荐答案
我认为这是不可能的。当查看 Dictionary
声明时,似乎没有办法更改值,只能替换它。这是有道理的,因为当你获得一个值时,它会返回字典中的真实结构的副本(结构总是被复制)。当然,它会在使用课程时起作用。这是我的理论..
I think it's impossible. When looking at the Dictionary
declaration, there seems to be no method to changing a value, only replacing it. It kind of makes sense because when you get a value, it returns a copy of the real struct in the dictionary (structs are always copied). Of course it would work when using a class. That's my theory..
编辑:我刚刚发现,它的工作没有转换为[String:String]和一个只有正确类型的字典: p>
I just found out that it does work without the cast to [String: String] and a dictionary with just the right type:
var sampleDict = ["dictionary" : [String: String]()]
sampleDict["dictionary"]?.updateValue("avalue", forKey: "akey")
sampleDict["dictionary"]?["akey"] = "avalue"
这篇关于为什么我不能投一个混合类型字典的值并更新值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!