Search code examples
swiftuiviewdidsetproperty-observer

Property Observer in Swift


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()          
        }
}

Solution

  • 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.