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 Object-Oriented Swift 2.0 Classes Introduction to Classes

Sebastian Shelley
Sebastian Shelley
1,388 Points

Question regarding scope

Shouldn't the variable "life" in the function "decreaseHealth" not be affected be available parameter since it's only available in the class and the not the function? Or is it only variables created within the function that are not available to the class (unless we return something) but variables created in the class are accessible to the function?

By the way these videos went from extremely easy to really hard very quickly haha

1 Answer

Nathan Tallack
Nathan Tallack
22,159 Points

This is the beauty of class objects. They carry around not just their properties but also the methods (functions within a class) that allow you to interact with them.

A good indicator that a method is changing the properties of the object it is part of is when you are changing self. properties. Anytime you are referring to self you are talking about the properties for the object that this method is a part of.

So, in this case as your method is changing self.life it is affecting the property of the object that the method is a part of.

I had the same problem you did. Everything suddenly got hard. What i did is went back to where it was easy and started watching/coding again. Second time around I made that conceptual leap and it suddenly got easy again. :)