Stuart Casarotto
Stuart Casarotto

Reputation: 1187

Difference between self.view.addSubview and view.addSubview

I have done a bunch of coding in swift and prefer to do a lot programmatically and I was wondering what the difference was between these two:

self.view.addSubview(someNewView)
view.addSubview(someNewView)

they both seem to work. Is one better for some reason? Are they actually that different?

If this is a dumb question or already answered it can be removed. Just a thought.

Upvotes: 0

Views: 1480

Answers (1)

Eddie K
Eddie K

Reputation: 513

There's no real difference, although you may see the use of self more often from previously Objective-C developers. From the docs:

In practice, you don’t need to write self in your code very often. If you don’t explicitly write self, Swift assumes that you are referring to a property or method of the current instance whenever you use a known property or method name within a method.

...

The main exception to this rule occurs when a parameter name for an instance method has the same name as a property of that instance. In this situation, the parameter name takes precedence, and it becomes necessary to refer to the property in a more qualified way.

https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Methods.html

Upvotes: 5

Related Questions