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
}
}
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 = ""
}