There is a keyword Self
which is allowed in two places - in protocols (see Jean-Philippe Pellet's answer) and as a result of class
methods:
extension A {
class func niceObject() -> Self? {
return nil
}
}
Unfortunately, this won't help you because the following is invalid
extension A {
class func niceObject() -> Self? {
//A can't be converted to Self
return A()
}
}
The error is caused by the fact that when you inherit from A
class B : A {
}
then
var b = B.niceObject()
would actually return an A
instance which is not convertible to Self
(Self
is B
)
@Grimxn found the correct solution (See his answer):
You have to add a required initializer to the base class, e.g.
class A {
@required init() {
}
}
and then you can call the initialiser using self()
extension A {
class func niceObject() -> Self {
return self()
}
}