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 Classes and Objects Classes and Their Methods

Henrik Thomsen
Henrik Thomsen
1,848 Points

Why does the challenge make me pass with and without self. in my code??

I passed the challenge with the following code: class Button { var width: Double var height: Double

init(width:Double, height:Double){ self.width = width self.height = height }

func incrementBy(points: Double) { self.width = width + points self.height = height + points } }

But can anybody please tell me why I am also able to pass the challenge if I provide: self.width = self.width + points self.height = self.height + points

in the incrementBy method?

What is the actual difference if any? Thanks in advance!!

2 Answers

Alex Budure
Alex Budure
12,350 Points

The only time you should use self is for initializers or when the method takes a local parameter that has the same name as a global parameter.

For example, at the top of the class you already defined the variable height. You can now call that variable as self.height or just height. They both mean the same thing.

If the code was func incrementBy(width: Double) then to use the global parameter width, you'd have to say self.width or else it would refer to the local parameter you passed in the method.

I hope that helps!

Henrik Thomsen
Henrik Thomsen
1,848 Points

Hi Alex,

Yea that really made it more clear to me. Appreciate the help!