how to make the code simpler and more reusable for navigation links with multi dimension dictionary in swiftui?

后端 未结 2 1939
旧时难觅i
旧时难觅i 2021-01-28 03:35

I have a multi-level dictionary that I need use to build navigation links. Now I have a 2-level depth dictionary:

let multiDimDict: [String: [[String: [String]]]         


        
2条回答
  •  南笙
    南笙 (楼主)
    2021-01-28 03:44

    I would start by abandoning the use of a dictionary and use a simple recursive struct that provides a more useful model:

    struct Item: Identifiable {
        let id = UUID()
        var title: String
        var children: [Item] = []
    }
    

    Then you can define a recursive View to display this model:

    struct NavView: View { 
        var item: Item
    
        var body: some View {
            NavigationView {
                List {
                    ForEach(item.children) { child in
                        if child.children.isEmpty {
                            Text(child.title)
                        } else {  
                            NavigationLink(destination: NavView(item:child)) {
                                Text(child.title)
                            }
                        }
                    }
                }.navigationBarTitle(item.title)
            }
        }
    }
    

    Then you can create your hierarchy as required and pass the root to your view:

    let root = Item(title:"",children:
        [Item(title:"A",children:
            [Item(title:"A1", children:
                [Item(title:"A11"),Item(title:"A12")]
                )]),
              Item(title:"B",children:
                [Item(title:"B1"),Item(title:"B2")]
            )]
    )
    
    NavView(item:root))
    

提交回复
热议问题