As the saying goes, you cannot do this, and for good reason. You cannot prove that you keep your promise. Consider this:
class AnotherSubclass: Class {} let x = AnotherSubclass().instance
So x should be AnotherSubclass according to your protocol ( Self ). But actually it will be Subclass , it is a completely different type. You cannot resolve this paradox if the class is final . This is not a limitation of Swift. This restriction will exist in any valid type system, since it admits a type conflict.
On the other hand, you can make instance return some consistent type in all subclasses (e.g. superclass). You do this with a related type:
protocol Protocol { typealias InstanceType var instance: InstanceType {get} } class Class: Protocol { var instance: Class {return Subclass()} } class Subclass: Class {} class AnotherSubclass: Class {} let x = AnotherSubclass().instance
Now x uniquely Class type. (This is also a random other subclass that looks weird, but this is what the code says.)
By the way, all this usually assumes that you use subclasses when you really should not. Composition and protocols probably solve this problem better in Swift. Ask yourself if there is any reason why Subclass should be a subclass of Class . Could it be an independent type that conforms to the same protocol? All problems disappear when you get rid of subclasses and focus on protocols.
I thought about it more, and there may be a way to get what you are looking for. Instead of saying that all subclasses implement instance , attach instance to the extension. You can still override this if you want to return something else.
protocol Protocol { init() } class Class: Protocol { required init() {} var instance: Class { return Subclass() } } extension Protocol { var instance: Self { return self.dynamicType.init() } } class Subclass: Class {}
This avoids the inheritance problem (you cannot create the same β AnotherClass returning the wrong typeβ this way).
source share