Swift: static func VS class func
Table of Contents
Recently I was confronted with a code where I saw for the first time the keyword class func. And I must admit, I had no idea what it was about. But as usual I remedied the situation and I wanted to share my discovery with you.
static func #
You should already be familiar with static func. If like me you started with languages like C# or Java you already had the opportunity to meet it.
It is simply a method accessible directly from a class and not from the instance of a class.
It is characterized with code like this:
final class MyClass {
static func getData() -> Data {
...
}
}
Nothing very complicated, not to say standard. In the above mentioned languages a class defining a static method and having a child class, this class will inherit the static method. It will be able to use it when needed but in no case redefine it. It is the same thing with Swift.
But we will see that it is different with the class func notation.
class func #
The Swift documentation says this:
Classes can use the class keyword instead, to allow subclasses to override the superclass’s implementation of that method.
You will have understood, unlike static func, it is possible here to override the method marked class func, very convenient in the case of inheritance.
So it is possible to do this:
|
|
The output is then :
I'm <MyClass>
I'm a subclass <MySubClass>
The keyword self #
In this particular case the self keyword is not used in the same way as usual:
Within the body of a type method, the implicit self property refers to the type itself, rather than an instance of that type. This means that you can use self to disambiguate between type properties and type method parameters, just as you do for instance properties and instance method parameters.
And yes in this case we are not in an instance method, therefore self cannot refer to the current instance of the class since it does not exist.
self therefore refers to the type of the class as in the example below:
class MyClass {
class func doIt() {
print("I'm <\(self)>")
}
}
Conclusion #
It is very interesting to have this possibility in Swift, it gives even more perspective for the management in the inheritance of classes. But it must be used wisely.