When should I access properties with self in swift?

后端 未结 6 2006
一生所求
一生所求 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:38

    I'm going to go against the flow and not use self unless absolutely required.

    The reason why is that two of the main reasons to use self is

    • When capturing self in a block
    • When setting self as a delegate

    In both cases, self will be captured as a strong reference. This might be what you want, but in many cases, you actually want to use a weak one.

    Therefor, forcing the developer to use self as an exception and not a rule will make this strong capture more conscious, and let him reflect on this decision.

提交回复
热议问题