【问题标题】:Protocol composition confusing协议组成混乱
【发布时间】:2019-07-16 12:29:48
【问题描述】:

我有 SocketIORepresentable 和 Typeable 协议。 Typeable 是带有关联类型的协议。为什么我尝试在我的 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) {

}

【问题讨论】:

  • 哪一行有什么错误?
  • in func sendRequest

标签: swift swift-protocols associated-types


【解决方案1】:

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 { ... }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-12-08
    • 1970-01-01
    • 2023-03-27
    • 2018-02-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多