Difference between using self and not using self in Swift init
Asked Answered
W

1

5

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?

Wini answered 29/9, 2014 at 11:57 Comment(0)
C
11

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.

Colcannon answered 29/9, 2014 at 12:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.