Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS

Trevor Duersch
Trevor Duersch
9,964 Points

Reference of instance variable vs. self.variable?

I am currently watching this training video (https://teamtreehouse.com/library/using-static-table-views) and at 5:45, I noticed Pasan used "self.photo" and on the next line used "selectedFilter." These are both instance variables.

Now with my experience with swift it seems that it doesn't matter, but when do you use self and other times not include self? I understand that you wouldn't use self with static class variables (such as referring to a variable that is of a Class type not instance/object). I'm guessing self is implicitly implied? Is that a safe assumption?

Thanks!

3 Answers

Paolo Scamardella
Paolo Scamardella
24,828 Points

You do not need to use self UNLESS you are inside a closure.

Trevor Duersch
Trevor Duersch
9,964 Points

You mean "You do not need to use self UNLESS you are inside a closure.", right? Then if that's the case, that makes sense. Thank you!

Paolo Scamardella
Paolo Scamardella
24,828 Points

Yes, I meant "You do not need to use self UNLESS..." Anyways, updated my first response to be correct.

Paolo Scamardella
Paolo Scamardella
24,828 Points

Also, I forgot...you need to use self inside the constructor (or any methods) if both the parameter that is being passed in and instance variable have the same name.

For example:

class Dog {
   let weight: Int

   init(weight: Int) {
      // you need to distinguish the difference between the parameter and instance variable
      self.weight = weight
   }
}