Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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!