0

I'm developing an iOS app and have the following data model:

struct Student {
    var name: String?
    var age: UInt?
    var hobbies: String?
    ...
}

This model is used as the data source in one view controller, where each property value will be filled in an UITextfield instance so that the user can edit a student's information. Every time a user finishes typing an item, e.g. the name, the new value will override the old model's corresponding property.

The problem is, since struct is a value type instead of a reference type, a new model instance is generated every time I assign a new property value to it. There may be above 20 properties in my model and I think so many copies are quite a waste. For some reasons I'm not allowed to use class. Is there any way to optimize this? Will these copies cause any performance issues?

P. Tsin
  • 435
  • 4
  • 14
  • 3
    First, if you are just updating the properties of the existing `Student` instance (which is why I assume you used `var` for all those properties), that will not make a new copy every time. I suspect you have misinterpreted value semantics. But, if you have some code that is creating a new instance, edit your question to include that. Second, even if the language did make a new copy every time you mutated a property (which it doesn’t), this smacks of premature optimization. Or have you benchmarked it and found an observable impact? – Rob Dec 08 '21 at 16:06
  • @Rob Oh, you are right. I just did a test and it did not make a new copy as you said. The reason I misinterpret value semantics is that I have a **didSet** block associated with my Student instance and whenever a property is updated this block is executed, this makes me think that a new instance copy is made. – P. Tsin Dec 08 '21 at 16:19
  • @Rob What exactly happens when you mark a property as mutable? – Rajesh Budhiraja Dec 09 '21 at 13:42
  • @RajeshBudhiraja - When you declare a property with `var` it can be mutated (without requiring the whole object that contains that property to be re-copied). When you declare a property with `let`, it is a constant and cannot be mutated. (As an aside, whenever a value will not change, we generally favor immutable constants over mutable variables, where possible, as it makes it easier for us to reason about our code.) – Rob Dec 11 '21 at 19:18

1 Answers1

0

you can create a func with mutating keyword like below

 struct Point {
      var x = 0.0
      mutating func add(_ t: Double){
        x += t
     }
   }

find more here

FaFa
  • 59
  • 10