简体   繁体   中英

How do I select a specific id from a JSON file in swift?

I'm trying to just select one of the entries in my JSON file and am struggling to do so. Here is the list part of my code so far:

    var body: some View {
        
        NavigationView {
            Group {
                List {
                    ForEach(regions) { regions in
                   NavigationLink(destination: RegionsListView(regions: regions)) {
                       RegionButtonView(regions: regions)
                   }
              }
        }
            }
        }
        }

And here is the if statement :

    let regions: Region
    
    var body: some View {
        if regions.id != nil {
            SCaliView()
        } else if regions.id != nil {
            BAView()
        }
    }
}
struct Region: Codable, Identifiable {
    let id: Int
    let name: String
    let image: String

}

I want to make it so that when a certain id is selected, it will go to a certain view.

You can literally throw whatever kind of view you'd like after the case using a ViewBuilder. Text Views, Nested Stacks although its a little clear passing pre-constructed views. Just replace the Int with whatever you id type is, although Int should work and then modify the case statements to handle your different ids

 @ViewBuilder func jsonSelector(using id: Int) -> some View {
      switch id {
         case 0:
      ViewA()
         case 1: 
      ViewB()
         case 2: 
      ViewC()
         case 3: 
      ViewD()


     }

}

Then just throw it in your view

jsonSelector(using: myID)

If you add some code, I'll edit the answer to fit your use case but this is a general fix

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM