简体   繁体   中英

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM