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?
self
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.
Meta-types
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 Dog
type 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
.
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.