JoseMartinFit JoseMartinFit - 5 months ago 28
Swift Question

Array of structs with this Dictionary in Swift

I'm being helped with this: tableViews with dictionary

I was able to reproduce all. But I need my dictionary to be like this:

var channelsCategorized = [String:[String:Int]]()

Now to iterate with every value from the dictionary the link above says to do this:

for (key,value) in channelsCategorized{

structArray.append(channelsStruct(section: key, name: value))


This is if my dictionary was [String:[String]] but it's [String:[String:Int]]. I need it to add to the struct section, name and id. My dictionary it's something like this:

This is my struct:

struct channelsStruct {

var section: String!
var name: [String]!
var channelId: String!

and this is my struct array:

var structArray = [channelsStruct]()


I put the following together which should show how to implement this in your case. Note I've included a check so that the struct is only created if all the values are available.

let myDictionaryOfDictionaries : [String : [String : String]] = ["Apples" : ["Colour" : "Red", "Type" : "Granny Smith"],
                                             "Oranges" : ["Colour" : "Orange", "Type" : "Seville"]]

struct fruit {
    let name : String
    let colour : String
    let type : String

var fruits : [fruit] = [fruit]()

for (key, value) in myDictionaryOfDictionaries {

    if let colour : String = value["Colour"], let type : String = value["Type"] {
        let newFruit = fruit(name: key, colour: colour, type: type)

print(fruits.count) // Outputs 2

for f in fruits {
    print("NAME: \( COLOUR: \(f.colour) TYPE: \(f.type)") //Outputs NAME: Apples COLOUR: Red TYPE: Granny Smith\n NAME: Oranges COLOUR: Orange TYPE: Seville