如何将类型传递给函数?

时间:2019-12-24 03:30:46

标签: swift protocols associated-types

我试图弄清楚如何在运行时设置关联类型。到目前为止,我有这个

class NetworkManager: NetworkManaging {

    private let service: NetworkServicing

    init(api: EndPointType) {
        let type = type(of: api.self)
        service = NetworkService<type>()
    }

}


protocol NetworkServicing: class {
    associatedtype EndPoint: EndPointType
    func request(_ route: EndPoint, completion: @escaping NetworkRouterCompletion )
}

class NetworkService<EndPoint: EndPointType>: NetworkServicing {
    func request(_ route: EndPoint, completion: @escaping NetworkRouterCompletion) {
        // make request
    }

}

但是我得到这些错误:

Protocol 'NetworkServicing' can only be used as a generic constraint because it has Self or associated type requirements

Variable used within its own initial value

Use of undeclared type 'type'

我只是误解了关联类型如何工作?

0 个答案:

没有答案