Home > Mobile >  How Can I Put a Dictionary Inside An Array That's Nested In Another Dictionary? (Swift)
How Can I Put a Dictionary Inside An Array That's Nested In Another Dictionary? (Swift)

Time:12-27

I want to add an array of dictionaries to an existing dictionary.

var details: [String : [String : String]] = [:]
viewDidLoad()
...
    for i in 0..<count {
        let hour = makeHourString()
        details[hour] = [String: String] () as [String : String]
        let dict = ["detailKey": "2100xx", "detailImage":"base64xx"]
        details[hour].append(dict)
    }
...

It is telling me: Value of type '[String : String]' has no member 'append.' But shouldn't it since it's an array?

I can get this kind of nested dictionary if I change the code to:

var details: [String: [Any]] = [:]
viewDidLoad()
...
    for i in 0..<count {
        let hour = makeHourString()
        details[hour] = [String] () as [String]
        let dict = ["detailKey": "2100xx", "detailImage":"base64xx"]
        details[hour].append(dict)
    }
...

Unfortunately, this isn't working for me because I need to able to store my data source using Codable. Any help is greatly appreciated.

CodePudding user response:

This [String : String] is a Dictionary not an Array , According to your case you need

var details: [String: [[String:String]]] = [:]

and off course you can do this also

var details: [String:[Item]] = [:]

With

struct Item {
   let detailKey, detailImage:String
}
  • Related