协议组成混乱

Protocol composition confusing

我有协议 SocketIORepresentable 和 Typeable。 Typeable 是带有 associatedType 的协议。为什么我尝试在我的函数中创建协议组合时出现错误?

swift 5.0

import Foundation

protocol Typeable {
    associatedtype Item: Decodable
    var responseType: Item.Type { get }
}


protocol SocketIORepresentable {
    func representable() throws -> [Any]
}

extension SocketIORepresentable where Self: Encodable {
    func representable() throws -> [Any] {
        let tempSendData = try JSONEncoder().encode(self)
        return [try JSONSerialization.jsonObject(with: tempSendData, options: .allowFragments)]
    }
}

public struct APIRequest: Encodable {
    let type: String
    let payload: Data
    let ts = Date()
}

extension APIRequest: SocketIORepresentable {}

public struct Request<T: Decodable>: Typeable {
    let apiRequest: APIRequest
    var responseType: T.Type
    public init(apiRequest: APIRequest) {
        self.apiRequest = apiRequest
        self.responseType = T.self
    }
}

private func sendRequest<T: Typeable>(_ request: T & SocketIORepresentable, completion: @escaping (Result<T.Item, Error>) -> Void) {

}

T 不是协议。 T是符合Typeable的具体类型。然后你不能说 request 必须是 "of the concrete type T and also conforms to SocketIORepresentable." 你的意思是 T 是一个符合以下两者的具体类型:

private func sendRequest<T: Typeable & SocketIORepresentable>(_ request: T, completion: @escaping (Result<T.Item, Error>) -> Void) { ... }

通常你会用 where 子句来写这个以避免这么大 angle-bracket:

private func sendRequest<T>(_ request: T, completion: @escaping (Result<T.Item, Error>) -> Void)
    where T : Typeable & SocketIORepresentable { ... }