solidcell
solidcell

Reputation: 7739

Can a property observer be added after the initial declaration?

For example, I'd like to call a method on a class instance that will add a willSet to a property. I'd like to not have to specify the willSet in the declaration of the property, since I'd need to add conditional logic within the observer, and it would be unnecessarily run for every other instance that hasn't had this method called.

Something like this:

var someProperty: Int

func someMethod() {
    someProperty {  // this is the syntax/ability I'm unsure about
        willSet { ...add some behavior... }
    }

    ...more stuff...
}

Upvotes: 6

Views: 621

Answers (1)

cmyr
cmyr

Reputation: 2275

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, where you have an optional closure that you evaluate in the willSet, and you only assign something to that property when you want the observing behaviour.

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 isn't especially elegant, but it might more-or-less handle the behaviour you desire?

Upvotes: 3

Related Questions