简体   繁体   English

协议的指定初始化程序类

[英]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.

相关问题 在Swift类的指定初始值设定项中调用实例方法 - Calling an instance method in designated initializer of a Swift class 无法在NSManagedObject类上调用指定的初始化程序-CoreData - Failed to call Designated Initializer on NSManagedObject Class — CoreData Swift:在类中实现协议初始化器 - Swift: Implementing Protocol Initializer in a Class CoreData:错误:无法在NSManagedObject类上调用指定的初始化程序 - CoreData: error: Failed to call designated initializer on NSManagedObject class CoreData:错误:无法在创建时失败的NSManagedObject类上调用指定的初始化程序 - CoreData: error: Failed to call designated initializer on NSManagedObject class failing on create Segue错误-无法在nsmanagedobject类上调用指定的初始化程序 - Segue error - failed to call designated initializer on nsmanagedobject class CoreData:错误:无法在NSManagedObject类“ Video”上调用指定的初始化程序 - CoreData: error: Failed to call designated initializer on NSManagedObject class 'Video' Swift CoreData:错误:无法在NSManagedObject类'NSManagedObject'上调用指定的初始值设定项 - Swift CoreData: error: Failed to call designated initializer on NSManagedObject class 'NSManagedObject' NSWindowController指定初始化器拼图 - NSWindowController designated initializer puzzle UITextView 的指定初始化器 - Designated Initializer of UITextView
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM