SwiftUI View instances

does anyone know why when i create an instance of a view by typing it names and then putting parentheses after it, in a for loop, the View shares data amongst the instances? i need unique values within an instance


Here's the code to my view:


struct SwiftUIView: SwiftUI.View {
 
    private let currentDB: [my_Section] = loadDB()
    private let subcurrentDB: [my_subSection] = loadSubsubsections()
    @ObservedObject var first_value: section_array
   // @Binding var current_section: ContentView.my_Section
   // @State private var comment: String = String()
   var body: some SwiftUI.View {
      

       
        Picker(selection: $first_value.first_value, label: Text("Subsection")) {
                                            
            ForEach(0 ..< self.subcurrentDB.count) {
                                                
                                            
                Text(self.subcurrentDB[$0].details)
                                                 
                                                 
       
            }
        }
    }
           
    }


Here's how I create the view...


     ForEach(master_subsections) { result in
                                SwiftUIView(first_value: self.first_value)
                           
                           
                        }

Replies

Could you explain:


when i create an instance of a view by typing it names and then putting parentheses after it, in a for loop, the View shares data amongst the instances?


  • Do you refer to line 17 or line 2 ????
  • Which data precisely is getting shared ? Between who precisely ?

I refer to line 2.


In reference to the next remark:

  1. private let currentDB: [my_Section] = loadDB()
  2. private let subcurrentDB: [my_subSection] = loadSubsubsections()
  3. @ObservedObject var first_value: section_array


the first_value ObservedObject is changed on every instance of my SwiftUIView() being created in line 2.

I must miss something obvious in your problem.


You call ForEach, so for each view that is called, you set the first_value. Isn't it what is expected ? Which single view would you expect to be updated ?

Sorry, I posted old code. first_value is not passed to my view, infact, my view has a first_value defined. So, when I create an instance of SwiftUIView() every SwiftUIView() that is added to my page shares the same result after picking a solution. Does that make sense

So, please, post the correct version of code. That will be easier than trying to transpose the explanation.