我希望创建一个非常通用的服务层,它可以调用Alamofire。见代码:
func getRequest(from endpoint:String!, withParameters parameters:[String:Any]?,withModel model:RuutsBaseResponse, andCompleteWith handler:@escaping (RuutsBaseResponse?, NSError?) -> ()){
func generateModel(withResponse result:NSDictionary?, withError error:NSError?) -> (){
handler(model.init(fromDictionary: result),error);
}
alamoFireService.AlamoFireServiceRequest(endpoint:endpoint, httpVerb:.get, parameters:parameters!, completionHandler:generateModel);
}
这就是RuutsBaseResponse的样子:
protocol RuutsBaseResponse {
init(fromDictionary dictionary: NSDictionary);
}
getRequest
希望执行以下操作:
RuutsBaseResponse
协议,就可以在任何班级中使用。generateModel
时,该方法应该实例化模型并传入其中,字典从alamoFire接收。 问题是模型,我正努力达到上述要求。我一直在说:
错误:(22,21)' init'是该类型的成员;使用'类型(of:...)'至 初始化相同动态类型的新对象
我要做的就是创建一个足够通用的层来进行服务调用,并创建一个从alamoFire传回的Dictionary创建的对象/模型。
答案 0 :(得分:0)
您要找的是如何使用Generics:
protocol RuutsBaseResponse {
init(fromDictionary dictionary: NSDictionary);
}
struct BaseModel: RuutsBaseResponse {
internal init(fromDictionary dictionary: NSDictionary) {
print("instantiated BaseModel")
}
}
struct SecondaryModel: RuutsBaseResponse {
internal init(fromDictionary dictionary: NSDictionary) {
print("instantiated SecondaryModel")
}
}
// state that this function handles generics that conform to the RuutsBaseResponse
// protocol
func getRequest<T: RuutsBaseResponse>(handler: (_ response: T) -> ()) {
handler(T(fromDictionary: NSDictionary()))
}
getRequest(handler: { model in
// will print 'instantiated BaseModel'
(model as! BaseModel)
})
getRequest(handler: { model in
// will print 'instantiated SecondaryModel'
(model as! SecondaryModel)
})