user89862
user89862

Reputation:

Bypass setter for property in swift

I want to set a property in my own class which has got a setter without that setter being called. Is that possible?

override var textColor: UIColor? {
    set {
        super.textColor = newValue
        // some additional code here
    }
    get {
        return super.textColor
    }
}

I tried to set like this _textColor = UIColor.blackColor() but that doesn't work. I want "some additional code" to only run when textColor is set from outside and not from within my own class.

Upvotes: 0

Views: 350

Answers (2)

Antonio
Antonio

Reputation: 72810

If you need dual access control, you can create a private stored property, and expose it outside via a computed property. However in your case the stored property is already implemented in the superclass, so that solution "as is" won't work.

The only way to achieve what you need is to create 2 computed properties, one for external usage, the other one for internal:

private var _textColor: UIColor? {
    get { return super.textColor }
    set { super.textColor = newValue }
}

override var textColor: UIColor? {
    get { return super.textColor }
    set {
        super.textColor = newValue
        // Additional processing here
    }

But in this case you have to remember to use the private one from within the class code

Upvotes: 1

idmean
idmean

Reputation: 14915

This is not possible. You’ll have to define an additional variable and keep it private. E.g.

private var _textColor: UIColor?
override var textColor: UIColor? {
    set {
        _textColor = newValue
        super.textColor = newValue
        // some additional code here
    }
    get {
        return _textColor
    }
}

Upvotes: 0

Related Questions