我有一个协议如下
public protocol AdvancedWebSocketRequestProtocol: AnyObject {
associatedtype ModelType: Codable
var socketPath: String { get }
var response: ModelResponse<ModelType>? { get set }
var responseHandler: ((ModelType?, ServiceError?) -> Void)? { get set }
func successListener(data: ModelType) -> Void
func failureListener(error: ServiceError) -> Void
}
然后,我创建了一个符合该协议的对象
public class MyStocksWebSocketRequest: AdvancedWebSocketRequestProtocol {
public typealias ModelType = [InvestmentStockResponse]
public var socketPath: String = "/socket"
public var config: [SocketIOClientConfiguration] = []
public var response: ModelResponse<[InvestmentStockResponse]>?
public var responseHandler: (([InvestmentStockResponse]?, ServiceError?) -> Void)?
public func successListener(data: ModelType) { }
public func failureListener(error: ServiceError) { }
}
然后我想有一个WebSocketManager
类,并存储一个符合AdvancedWebSocketRequestProtocol
的对象。因为有许多请求类符合相同的协议,我希望能够传递它们。
这就是它的样子
class WebSocketManager {
private let request: AdvancedWebSocketRequestProtocol
private let manager: SocketManager
private let socket: SocketIOClient
init(request: AdvancedWebSocketRequestProtocol) {
self.request = request
}
}
我得到以下错误,但我不认为这是正确的解决方案。
Use of protocol 'AdvancedWebSocketRequestProtocol' as a type must be written 'any AdvancedWebSocketRequestProtocol'
有没有什么方法可以存储对象并将其传递给WebSocketManager
?
1条答案
按热度按时间7vux5j2d1#
您可以使类成为泛型
或者您可以按照错误消息中的建议使用
any