[英]Designated Initializer Class for a Protocol
I'd like to use a protocol name as an initializer. 我想将协议名称用作初始化程序。 Something like this:
像这样:
protocol Foo { ... }
protocol Bar : Foo { ... }
class FooImpl : Foo { ... }
where let foo = Foo()
will defer to FooImpl()
when assigning to foo
. 分配给
foo
时, let foo = Foo()
将FooImpl()
。 Is there a way to specify a 'designated initializer class' for a protocol? 有没有一种方法可以为协议指定“指定的初始化程序类”?
Another option might be: 另一个选择可能是:
class Foo {
class FooImpl { ... }
init () {
// somehow create a FooImpl
}
}
Is the above possible? 以上可能吗? But, not sure this second case is practical given that properties can't be declared in
Foo
unless they are implemented therein. 但是,不确定第二种情况是否可行,因为除非在
Foo
中实现属性,否则无法在Foo
声明属性。
I'd use the factory pattern here: 我会在这里使用工厂模式:
class FooFactory {
class func createFoo -> Foo {
return FooImpl()
}
}
...
let foo = FooFactory.createFoo()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.