gpt4 book ai didi

swift - 如何通过 Swift 3 中的协议(protocol)从类公开 init() 的接口(interface)

转载 作者:行者123 更新时间:2023-11-30 11:10:23 24 4
gpt4 key购买 nike

我想通过 swift 协议(protocol)在类中使用泛型类型:

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()在协议(protocol)中WebSocketType :

public protocol WebSocketType {
init()
}

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

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

最佳答案

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

关于swift - 如何通过 Swift 3 中的协议(protocol)从类公开 init() 的接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52250305/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com