Search code examples
swiftlistviewswiftuiswiftui-navigationlinkswiftui-navigationview

SwiftUI - Best approach for when each listview's contents is dependent upon the selection in the previous listview?


I have 3 simple arrays:

var myContintents = [Europe,Africa]
var myCountries = [UK, France, Senegal]
var myCities = [London, Birmingham, Paris, Dakar]

Each array populates a listview, with a navigationlink to the next listview

Listview 1 = Contintents
Listview 2 = Countries
Listview 3 = Cities

However, I am having trouble with how to make this dependant

For example,

If 'Europe' is chosen on Listview1, then Listview2 should only contain UK and France (not Senegal, as Senegal is not in Europe)

If 'France' is chosen on Listview 2, then Listview 3 should only contain Paris

Any recommended suggestions on how to handle this would be most welcome

Thanks


Solution

  • You should learn how to create your own custom types, for this scenario the following should be suitable

    struct Continent {
        let name: String
        let countries: [Country]
    }
    
    struct Country {
        let name: String
        let cities: [City] //Or skip the last struct and make this a [String]
    }
    
    struct City {
        let name: String
    }
    

    Now you have an array of Continent in your first list view and when one continent is selected then fill the next one with the countries on the countries array property

    Here is a small example

    let continents = [
        Continent(name: "Europe",
                  countries: [
                    Country(name: "UK",
                            cities: [
                                City(name: "London"),
                                City(name: "Birmingham")
                            ]),
                    Country(name: "France",
                            cities: [
                                City(name: "Paris")
                            ])
                  ])
    ]