I noticed that initializing a property in a Swift initializer works using both:
self.property = 1
and
property = 1
Is there any difference between the two? If not, is there a convention that favors one over the other?
In the first you're making explicit that it's a class/struct property, whereas in the 2nd it's implicit. There's one big difference though: if there's a local variable with the same name (such as a parameter passed to the init), it will take precedence and hide the class/struct property.
As a matter of preference, I always prefer making it explicit, by using self
. Also, by doing that I avoid common errors happening when I think I am accessing the class property, and I am using a local variable or function parameter instead.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With