Reputation: 363
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.
Upvotes: 1
Views: 282
Reputation: 70098
Your var caramelDelight = []
doesn't create an empty dictionary.
To create an empty dictionary use [:]()
and specify the types of the keys and values, example: var caramelDelight = [String:String]()
.
There's also this alternative syntax: var caramelDelight: [String:String] = [:]
.
Also to modify the var in your struct you need to create an instance of the struct first:
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]
Upvotes: 2
Reputation: 2147
That is because caramelDelight
is actually an array, not a dictionary. You can fix that by doing var caramelDelight: [String:String] = [:]
Upvotes: 1