teradyl
teradyl

Reputation: 2802

Difference between setting a variable on init and overriding that variable in Swift?

I'm working on accessibility, and I see some code in a project I'm working on that's overriding the isAccessibilityElement variable. How is this different and/or why is this better than just setting the variable in the init?

This is what I see in my project:

public override var isAccessibilityElement: Bool 
{
  get { return false }
  set { }
}

How is it different from this?

public init()
{
  super.init(frame: .zero)
  isAccessibilityElement = false
}

Upvotes: 1

Views: 122

Answers (1)

teradyl
teradyl

Reputation: 2802

I discovered the answer as I was asking the question.

When you write this code:

public override var isAccessibilityElement: Bool 
{
  get { return false }
  set { }
}

You prevent users of this view from changing that property by leaving the setter empty. If you just set the property in the init, then users of this class can still change that value, which could produce unwanted results.

However, doing it this way will also fail silently!!!

To reiterate: SETTING THIS VARIABLE WILL FAIL SILENTLY

Upvotes: 3

Related Questions