2017-07-28 121 views
0

的通用协议性能要求挣扎了一会儿有,这将是非常有益的,如果你可以在此提供一些线索:如何声明在协议

我有一个APIWorkerProtocol具有性能要求,所需财产是一个协议,即DataParserProtocol

protocol APIWorkerProtocol { 
    var apiRequestProvider : APIRequestGeneratorProtocol {get} 
    var dataParser : DataParserProtocol{get} 
    func callAPI(completionHandler: @escaping (APICallResult<Self.ResultType>) -> Void) 
} 

protocol DataParserProtocol { 
    associatedtype ExpectedRawDataType 
    associatedtype ResultType 
    func parseFetchedData(fetchedData : ExpectedRawDataType) -> APICallResult<ResultType> 
} 

我该怎么做到这一点?

在当前的实施中,这会导致错误Protocol 'DataParserProtocol' can only be used as a generic constraint because it has Self or associated type requirements

预先感谢

ANKIT

回答

1

如果协议化妆用途的Self或相关联的类型的要求(均匀的协议),我们可以注意到使用的协议作为具体类型。

因此,而不是使用DataParserProtocol作为具体类型dataParser属性(在APIWorkerProtocol blueprinted),你可以添加一个associatedtype typeholder,说DataParser,到APIWorkerProtocol,这被约束为符合类型DataParserProtocol

而且,我不知道用的callAPI(...)完成处理器使用Self.ResultType作为专业化的意图是什么(因为Self将引用类型实施APIWorkerProtocol;其蓝图没有associatedtypeResultType协议):你的意思要使用DataParserProtocol类型的ResultType

E.g.

protocol APIWorkerProtocol { 
    associatedtype DataParser: DataParserProtocol 
    var dataParser : DataParser { get } 
    func callAPI(completionHandler: @escaping (APICallResult<DataParser.ResultType>) -> Void) 
} 

protocol DataParserProtocol { 
    associatedtype ExpectedRawDataType 
    associatedtype ResultType 
    func parseFetchedData(fetchedData: ExpectedRawDataType) -> APICallResult<ResultType> 
} 
+0

你是绝对正确我的@dfri –