Swift: Use Self to let methods in subclass return instances of subclass

Sen Liu
1 min readAug 8, 2018

--

Many of us know Self can be used in protocols, but Self can also be used in classes.

Sometimes we have methods in a class which return instances of the class. The methods can be either instances method or class methods. For example:

Now we want to create a subclass MySubclass. With this implementation of MyClass, the methods in MySubclass can only return instances of MyClass instead of MySubclass. If we want to return instances of MySubclass, we need to use Self.

--

--