Reputation: 53142
Why doesn't this work:
protocol Work {
init()
static func make() -> Self
}
extension Work {
static func make() -> Self {
return self.init()
}
}
class Foo : Work {
required init() {}
}
I can make inheritance possible by adding the factory to the object itself:
class Foo : Work {
required init() {}
static func make() -> Self {
return self.init()
}
}
I could also use a non-class or mark the class final
, but I'd prefer/am required to use inheritance.
Is it possible to implement a default factory on a protocol so that an inheritable type can conform without implementing it again.
Upvotes: 0
Views: 49
Reputation: 7756
If you want a factory that will initialize objects adhering to a protocol, you should use the always awesome generics! E.g.
protocol Work {
init()
static func make<T: Work>(type: T.Type) -> T
}
extension Work {
static func make<T: Work>(type: T.Type) -> T {
return T.init()
}
static func make() -> Self {
return make(Self)
}
}
class Foo : Work {
required init() {}
}
Upvotes: 1