When should I access properties with self in swift?

The only times self is required are when referencing a property inside a closure and, as you pointed out, to differentiate it from a local variable with the same name.

However, personally, I prefer to always write “self” because:

  1. That is an instant and obvious sign that the variable is a property. This is important because it being a property means that its state can vary more widely and in different ways than a local variable. Also, changing a property has larger implications than changing a local variable.
  2. The code does not need to be updated if you decide to introduce a parameter or variable with the same name as the property
  3. Code can be easily copied in and out of closures that do require self

Leave a Comment