Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift public var with default value and run didSet for that default value [duplicate]

I have my Swift class as the simple code below:

class FavoriteView: UIView {
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        commonInit()
    }
    override init(frame: CGRect) {
        super.init(frame: frame)
        commonInit()
    }
    convenience init() {
        self.init(frame: CGRectZero)
    }
    private func commonInit() {
        // init something
    }

    // MY PROBLEM IS HERE
    var favoriteCount: Int = 0 {
        didSet {
            // update the view
        }
    }
}

The logic is whenever the favoriteCount is set to a new value, the code in didSet is run.

It runs well. But the problem is that code (in didSet) is not run for the very first time. I mean when a new FavoriteView instance is initialized, I assume it to run also, but it's not.

Is there any way to run that code (in didSet) for the first time.

Thank you!

like image 633
vietstone Avatar asked Sep 19 '16 11:09

vietstone


1 Answers

didSet observer not invoked with default values, as well as it not invoked when you setting up properties in init methods (due to self not initialized yet). You may write separated method updateView and invoke it in init method and in didSet observer.

private func commonInit() {
    updateView()
    // init something
}

// MY PROBLEM IS HERE
var favoriteCount: Int = 0 {
    didSet {
        updateView()
    }
}

func updateView() {
    //code that you wanted to place in observer
}
like image 149
Shadow Of Avatar answered Nov 15 '22 16:11

Shadow Of