将遵循给定协议的类传递到方法中,然后使用swift实例化该类



我希望创建一个非常通用的服务层,看起来可以调用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);
    }

ruutsbaserresponse是这样的:

protocol RuutsBaseResponse {
    init(fromDictionary dictionary: NSDictionary);
} 

getRequest看起来做以下事情:

  1. 只要符合RuutsBaseResponse协议,就可以在任何类中使用。
  2. 使用传入的参数使用alamoFire进行服务调用。
  3. alamoFire将在服务调用完成后调用generatmodel方法。
  4. 当它调用generateModel的方法应该实例化模型,并传递到它从alamoFire收到的字典。

问题是模型,我正在努力实现上面的要求。我一直收到:

错误:(22日,21)'init'是类型的成员;使用'type(of:…)'来初始化相同动态类型的新对象

我所要做的就是使一个层通用到足以进行服务调用,并创建一个对象/模型,该对象/模型是从alamoFire传回的字典创建的。

您正在寻找的是如何使用泛型:

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)
})

最新更新