Can a property observer be added after the initial declaration?

For example, I would like to call a method on an instance of a class that will add the willSet property to the property. I would not want to specify willSet in the property declaration, since I would need to add conditional logic in the observer, and this would be unnecessarily launched for every other instance that did not have this method called.

Something like that:

 var someProperty: Int func someMethod() { someProperty { // this is the syntax/ability I'm unsure about willSet { ...add some behavior... } } ...more stuff... } 
+6
source share
1 answer

An observer can be added to a property declared in a superclass, but not in the same class or in a class extension. You cannot declare the same property in two places in a function. The best solution I can come up with is something like this, when you have an optional closure that you evaluate to willSet, and you only assign something to this property when you want to observe the behavior.

maybe something like:

 private var _willSetCallback: ((Int) -> (Bool))? var someProperty: Int { willSet { if let optionalBool = _willSetCallback?(newValue) { // do something } } } func someMethod() { self._willSetCallback = { newValue in return newValue > 0 } } 

It is not particularly elegant, but can he more or less cope with the desired behavior?

+3
source

Source: https://habr.com/ru/post/976945/


All Articles