Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between using self and not using self in Swift init

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?

like image 797
Youssef Moawad Avatar asked Sep 29 '14 11:09

Youssef Moawad


1 Answers

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.

like image 190
Antonio Avatar answered Sep 30 '22 15:09

Antonio