简体   繁体   中英

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.

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]

That is because caramelDelight is actually an array, not a dictionary. You can fix that by doing var caramelDelight: [String:String] = [:]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM