我想通过快速协议在类中使用泛型类型:
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 a
,initializer in non-final class 'WebSocket'
。
如何解决此问题以在类中构造泛型?
答案 0 :(得分:0)
WebSocket
的子类不必继承WebSocket
的所有初始值设定项。因此,WebSocket
的子类可能无法符合WebSocketType
。解决方案是用WebSocket
声明final class WebSocket
使其不能被子类化,或者将WebSocket
的初始化器声明为required init()
以便所有子类也必须提供它。然后,WebSocket
将符合WebSocketType
,从而解决您的问题。