为什么这不起作用:
protocol Work {
init()
static func make() -> Self
}
extension Work {
static func make() -> Self {
return self.init()
}
}
class Foo : Work {
required init() {}
}
我可以通过将工厂添加到对象本身来使继承成为可能:
class Foo : Work {
required init() {}
static func make() -> Self {
return self.init()
}
}
我也可以使用非类或将类标记为final
,但我更喜欢/需要使用继承。
是否可以在协议(protocol)上实现默认工厂,以便可继承类型无需再次实现即可符合要求。
最佳答案
如果你想要一个工厂来初始化遵守协议(protocol)的对象,你应该使用总是很棒的 generics ! 例如
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() {}
}
关于swift - 使用继承时,为什么不能为在协议(protocol)中返回 Self 的 Type 函数提供默认实现?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36212549/