协议组成令人困惑

时间:2019-07-16 12:29:48

标签: swift swift-protocols associated-types

我有SocketIORepresentable和Typeable协议。 Typeable是与associatedType协议。尝试在func中创建协议组成时为什么出错?

迅速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) {

}

1 个答案:

答案 0 :(得分:3)

T不是协议。 T是符合Typeable的具体类型。然后,您不能说request必须是“ T的具体类型,并且还必须符合SocketIORepresentable。”您的意思是T是同时符合两者的具体类型:

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

通常,您应该使用where子句来编写此代码,以避免出现这么大的尖括号:

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