Search code examples
swiftuitableviewios9sections

How to access a Data Model [String: [String]] in UITableView with sections?


I'm trying to prep my Data Model so it can be used in a UITableView with sections.

var folderHolder: [String: [String]]?

folderHolder = ["Projects": ["All", "Recent"], "Smart Folders": ["Folder 1", "Folder 2", "Folder 3"]]

How can I access the keys and objects in this dictionary via an index (as needed by the UITableView)

I tried this in the playground and got stuck. Thank you for your help with this.

// Need number of Keys
// Expected result: 2
folderHolder!.count

// Need number of elements in Key
// Expected: All and Recent are in Projects, so 2 would be expected
folderHolder!["Projects"]
folderHolder!["Projects"]!.count

// How can I get this result by stating the index, e.g. writing 1 as a parameter instead of "Smart Folders"
folderHolder![1]!.count

// Need specific element
// Input parameter: Key index, Value index
// Expected: "Folder 2"
folderHolder![1]![1]

// I don't know why it only works when I state the key explicitly.
folderHolder!["Smart Folders"]![1]

Screenshot with Playground results


Solution

  • Found out the solution after a bit more research:

    The Dictionary keys need to be converted into an array. The array items can be accessed via an index (the section of the UITableView) and return the name of the Key. And the name of the key can be used to access the Value of the Dictionary (the row of the UITableView).

    Here the correct playground data as a reference:

    var folderHolder: [String: [String]]?
    
    folderHolder = ["Projects": ["All", "Recent"], "Smart Folders": ["Folder 1", "Folder 2", "Folder 3"]]
    let folderHolderArray = Array(folderHolder!.keys)
    
    // Need number of Keys
    // Expected: 2
    folderHolder!.count
    folderHolderArray.count
    
    // Need number of elements in Key
    // Expected: All and Recent are in Projects, so 2 would be expected
    folderHolder!["Projects"]
    folderHolder!["Projects"]!.count
    // How can I get this result by stating the index, e.g. writing 1 as a parameter instead of "Smart Folders"
    folderHolderArray[1]
    
    
    // Need specific element
    // Input parameter: Key index, Value index
    // Expected: "Folder 2"
    //folderHolder![1]![1]
    let folderHolderSection = folderHolderArray[1]
    let folders = folderHolder![folderHolderSection]
    let folder = folderHolder![folderHolderSection]![1]