[英]Dictionaries not working inside a struct SWIFT
Why is this not working!? 为什么这不起作用!?
struct ChocolateBox {
var caramelDelight = []
caramelDelight["flavor"] = "caramel"
}
I tried this without the struct, still doesn't work: 我试过这个没有结构,仍然无法正常工作:
var caramelDelight = []
caramelDelight["flavor"] = "caramel"
I have to add initial values into the array for it to work, for example: 我必须在数组中添加初始值才能使其工作,例如:
var caramelDelight = ["test":"test"]
caramelDelight["flavor"] = "caramel"
Please explain. 请解释。
Your var caramelDelight = []
doesn't create an empty dictionary. 你的
var caramelDelight = []
不会创建一个空字典。
To create an empty dictionary use [:]()
and specify the types of the keys and values, example: var caramelDelight = [String:String]()
. 要创建空字典,请使用
[:]()
并指定键和值的类型,例如: var caramelDelight = [String:String]()
。
There's also this alternative syntax: var caramelDelight: [String:String] = [:]
. 还有这种替代语法:
var caramelDelight: [String:String] = [:]
。
Also to modify the var in your struct you need to create an instance of the struct first: 另外要修改struct中的var,首先需要创建struct的实例:
struct ChocolateBox {
var caramelDelight = [String:String]()
}
var cb = ChocolateBox()
cb.caramelDelight["flavor"] = "caramel"
println(cb.caramelDelight) // [flavor: caramel]
UPDATE: 更新:
You can also create an initializer for your struct if you need to prepopulate the dictionary: 如果需要预填充字典,还可以为结构创建初始化程序:
struct ChocolateBox {
var caramelDelight: [String:String]
init(dict: [String:String]) {
self.caramelDelight = dict
}
}
var cb = ChocolateBox(dict: ["flavor": "caramel"])
Of course then you can update the dictionary as usual: 当然,您可以像往常一样更新字典:
cb.caramelDelight["color"] = "brown"
println(cb.caramelDelight) // [color: brown, flavor: caramel]
That is because caramelDelight
is actually an array, not a dictionary. 那是因为
caramelDelight
实际上是一个数组,而不是字典。 You can fix that by doing var caramelDelight: [String:String] = [:]
您可以通过执行
var caramelDelight: [String:String] = [:]
来解决这个var caramelDelight: [String:String] = [:]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.