如何在Swift 3中通过协议从类公开init()的接口

时间:2018-09-10 02:26:31

标签: swift swift3

我想通过快速协议在类中使用泛型类型:

public protocol WebSocketType {
    // some interfaces
}

class _Network<WebSocketT: WebSocketType, Configuration: NetworkConfigurationType> {
    // Use the generic type
    let websocket: WebSocketT
    init(host: String, api: String) {
        // do something here...

        // create the instance which will conform the protocol via generic type
        // compilation error: 'WebSocketT' cannot be constructed because it has no accessible initializers
        self.websocket = WebSocketT() 
    }
}

// I'll create a class with concrete classes (WebSocket and NetworkConfiguration). 
// I don't have the class `WebSocket` and I'll extend that to conform the protocol `WebSocketType`.
extension WebSocket: WebSocketType {}
typealias Network = _Network<WebSocket, NetworkConfiguration>
let network = Network()

我遇到错误'WebSocketT' cannot be constructed because it has no accessible initializers,并在协议init()中添加了WebSocketType

public protocol WebSocketType {
    init()
}

然后我又遇到了另一个错误Initializer requirement 'init()' can only be satisfied by ainitializer in non-final class 'WebSocket'

如何解决此问题以在类中构造泛型?

1 个答案:

答案 0 :(得分:0)

WebSocket的子类不必继承WebSocket的所有初始值设定项。因此,WebSocket的子类可能无法符合WebSocketType。解决方案是用WebSocket声明final class WebSocket使其不能被子类化,或者将WebSocket的初始化器声明为required init()以便所有子类也必须提供它。然后,WebSocket将符合WebSocketType,从而解决您的问题。