When should I access properties with self in swift?

后端 未结 6 2007
一生所求
一生所求 2020-11-27 04:38

In a simple example like this, I can omit self for referencing backgroundLayer because it\'s unambiguous which backgroundLayer the backgroundColor is set on.



        
6条回答
  •  遥遥无期
    2020-11-27 05:19

    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

提交回复
热议问题