'Swift share data model communicate between page. how it works

I have a question. I have a DataModel from Class A passing to Class B. I would like Class B to retrieve the changed value from Class A. And They both can edit and share the same data. However, now Class B cannot get any value from Class A. How can i make it

struct DataModel {
  var firstName: String = ""
  var lastName: String = ""
}
class ClassA {

 var dataModel: DataModel

  
  ClassB(dataModel: dataModel)
  dataModel.firstName = "ABC"
}
class ClassB {
   var dataModel: DataModel

   init(dataModel: dataModel) {
     self.dataModel = dataModel

     dataModel.firstName <--- Print Null
  }
}


Solution 1:[1]

As struct is a value type when you pass A.dataModel to B, a copy of dataModel is passed to B, not the original instance.

So just use class for your data modal instead of struct if you want to modify A.dataModel in A as well as B

in other words you need to pass reference of A.dataModel to B

class DataModel {
    var firstName: String = ""
    var lastName: String = ""
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 IluSioN