如何在Swift中存储协议关联值?

smdncfj3  于 2023-09-30  发布在  Swift
关注(0)|答案(1)|浏览(89)

我有一个协议如下

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

7vux5j2d

7vux5j2d1#

您可以使类成为泛型

class WebSocketManager<Request: AdvancedWebSocketRequestProtocol> {
    private let request: Request

    init(request: Request) {
        self.request = request

    }
}

或者您可以按照错误消息中的建议使用any

class WebSocketManager {
    private let request: any AdvancedWebSocketRequestProtocol

    init(request: some AdvancedWebSocketRequestProtocol) {
        self.request = request

    }
}

相关问题