首页 文章

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

提问于
浏览
0

我正在寻找一个非常通用的服务层,它可以调用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 协议,任何类别都可以使用 .

  • 使用传入其中的参数使用alamoFire进行服务调用 .

  • alamoFire将在服务调用完成后调用generateModel方法 .

  • 当它调用 generateModel 时,该方法应该实例化模型并传入从alamoFire收到的字典 .

问题是模型,我正在努力达到上述要求 . 我一直在:

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

我所要做的就是创建一个足够通用的层来进行服务调用,并创建一个从alamoFire传回的Dictionary创建的对象/模型 .

1 回答

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

相关问题