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?
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.
© 2022 - 2024 — McMap. All rights reserved.