Swift:如何避免在所有继承类中重写此init()?

Swift:如何避免在所有继承类中重写此init()?,swift,Swift,我有一个框架中的类和协议: public protocol P {} open class C { public init(_ p: P.Type) { //super.init() etc } } 在使用此框架的项目中: enum E: P { // cases... } 困扰我的是,对于每个继承C的类,我都需要定义相同的init,如下所示: final class C1: C { init() { super.init(E

我有一个框架中的类和协议:

public protocol P {}

open class C {
    public init(_ p: P.Type) {
        //super.init() etc
    }
}
在使用此框架的项目中:

enum E: P {
    // cases...
}
困扰我的是,对于每个继承C的类,我都需要定义相同的init,如下所示:

final class C1: C {
    init() {
        super.init(E.self)
    }
}

final class C2: C {
    init() {
        super.init(E.self)
    }
}

// etc...
有没有一种方法可以让我在项目中声明此默认init,比如这样使用扩展:

extension C {
    // Declare the init(E.self) here somehow?
}
这样,我只需调用C1、C2等,而不用在子类中定义它


感谢您的帮助。

您可以创建一个包含init的协议,扩展该协议并提供默认实现,然后将该协议分配给C

public protocol P {}

enum E: P {
}

protocol A {
    init(_ p: P.Type)
}

extension A {
    init(_ p: P.Type) {
        // Add a default implementation
        self.init(E.self)
    }
}

class C: A {
    // If you want to override, note you need to add `required`
    required init(_ p: P.Type) {
    }
}

class C1: C {
    // No need to init here
}
或者,如果不需要其他协议,则需要一个实现init和子类C的新类,并让C1和C2继承这个新类。 当人们创建BaseUIViewController并将其UIViewController子类设置为以下类型时,通常会这样做:

public protocol P {}

enum E: P {
}

class C {
    init(_ p: P.Type) {
    }
}

class CBase: C {
    // Override and provide default implementation
    override init(_ p: P.Type) {
        super.init(E.self)
    }
}

class C1: CBase {
    // No need to init here
}

class C2: CBase {
    // No need to init here
}
申报

或者,您可以将方便的初始化器放在C的主定义中

extension C
{
    public convenience init()
    {
        self.init(E.self)
    }
}

let c1 = C1()
let c2 = C2()