Home > Enterprise >  Loop through Dictionary in SwiftUI
Loop through Dictionary in SwiftUI

Time:12-06

I have var countriesGroupedByRegion: Dictionary<String, [Array<Country>.Element]> The key (String) is the region and the array are all the countries within that region.

I need to loop through this dictionary so I can create a List with as much sections as regions, and within each section, I want to show all the countries... but I don't know how to loop through this dictionary in SwiftUI using ForEach. My current code is the following:

NavigationView {
  List {
    ForEach(countriesGroupedByRegion, id: \.self) { region in
                    
    }
  }
}

where countriesGroupedByRegion is the mentioned dictionary. I get the following error: Cannot convert value of type 'Dictionary<String, [Array<Country>.Element]>'

Could someone help me figure out how to loop through this dict and create the sections in SwiftUI?

CodePudding user response:

I recommend to map the (keys of the) dictionary to an array of a region struct

struct Region { 
    let name : String
    let countries : [Country]
} 

This can be used in a ForEach statement with id: \.name. Further consider that a dictionary is unordered.

This is a simple example with a string array representing the countries

let dictionary = ["Asia": ["Japan", "India"], "Europe": ["Italy", "Norway"]]

struct Region {
    let name : String
    let countries : [String]
}

let regions = dictionary
    .keys
    .sorted()
    .map{Region(name: $0, countries: dictionary[$0]!)}

NavigationView {
  List {
    ForEach(regions, id: \.name) { region in
                    
    }
  }
}
  • Related