Property Observer in Swift

614 Views Asked by At

Any idea how I can return a UIView from within didSet ?

I have a method that returns a UIView. I need to observe an Int and return a UIView as the Int changes. I have a didSet observer set, however, I get an error when trying to return the UIView.

Appreciate any help! Thanks.

func newUIView() -> UIView {

   var newUIView = UIView()

   return newUIView
}

var observingValue: Int = someOtherValue {
       didSet {
             //Xcode complains whether I use return or not
            return func newUIView()          
        }
}
2

There are 2 best solutions below

3
matt On BEST ANSWER

You say in a comment:

I guess my struggle is how to observe that value and react (update UI) to it accordingly

An observer is a perfectly good way to do that. But you don't return something; you call something. This is a very, very common pattern in Swift iOS Cocoa programming:

var myProperty : MyType {
    didSet {
        self.updateUI()
    }
}
func updateUI() {
    // update the UI based on the properties
}

At the time that the didSet code runs, myProperty has already been changed, so the method updateUI can fetch it and use it to update the interface.

2
Duncan C On

What you are asking doesn't make any sense.

A didSet is a block of code you add to an instance variable that gets invoked when anybody changes the value of that variable. There is no place to return anything.

If you need code that changes an instance variable and returns a view, you need to write a function:

func updateObservingValue(newValue: Int) -> UIView {
   observingValue = newValue
   return newUIView()
}