我有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) {
}
答案 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 { ... }