Self & Self.Type & self in Swift

You have probably already used the self keyword many times while writing code, but did you ever think what is the self? In the present article let’s cover next questions:
• What is self, Self, and Self.Type?
• When each of them is used?


As you probably already know, self is usually used when you need a reference to the object in the scope of which you are currently in. So, for example, if you use self inside an instance method of a Rocket struct, self, in this case will be an instance of that struct. That’s pretty easy to understand!

But what if you are going to use self inside a class method of a class instance or a static method of a struct instance? In this case, self cannot be a reference to an instance, because there is no instance and self has a value of the current type. It is because static and class methods exist on the type itself and not on an instance.


But wait! Here is a thing. All values should have a type, including self. As we learned before, static and class methods exist on the type, so in this case, self holds a type of Self.Type. It means that, for instance, Dog.Type will hold all Dog type values.

Types that hold other types are named meta-types.

To put it simply, this meta-type Dog.Type can not only hold the values of Dogtype but also all of its subclasses, like in the example below, where Labrador is a subclass of Dog .

You can also use type itself as a value if you want to store it somewhere in a variable or you need to pass it in a function. For that purpose, you would use it like so -Type.self .


Lastly, there is Self with a capital “S”. This one very straightforward since it always refers to a type in the current context. It can be useful when creating factory methods or returning the concrete type from a protocol method.

Thanks for reading!

if you enjoyed this article, be sure to give it a clap so others will find it more easily.




22 y.o. iOS Developer

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

A Comprehensive Guide to Using Alibaba Cloud DirectMail

How to Install Elgg on Alibaba Cloud ECS

Cautionary tale on developing disparate platforms

Risk management practices. Part 2


All you need to know about Google Cloud Dataproc?

My Top 3 SQL Interview Questions

The 10 Least Known Amazon AWS Services

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Sergey Chsherbak

Sergey Chsherbak

22 y.o. iOS Developer

More from Medium

Codable and key/property name not matching issue in Swift

[Swift] Struct vs Class

True or False?

Access specifiers in Swift