Swift copy attribute in initializer

883 views Asked by At

How do I ensure objects passed to an initializer are copied, rather than only on setting those attributes later?

Using @NSCopying, Apple says we can achieve copy-property-like behavior. Per default, the attribute is only assigned though, without calling the setter which does the copying.

This is potentially dangerous as I want to rely on the property being immutable and not being modified without me knowing. (think of getting an NSMutableString instead of NSString - copying would give me an immutable instance).

1

There are 1 answers

6
Tushar On
  1. Use @NSCopying while declaring the property.
  2. From within the initialiser call self.propertyname = newValue, so that the setter gets called and copying is done.
  3. To know when the value is being modified from outside of the class, implement the "set" observer (which also requires to implement get as well).