[英]Pass a class that follows a given protocol into a method and then instantiate the class using 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);
}
這是RuutsBaseResponse的樣子:
protocol RuutsBaseResponse {
init(fromDictionary dictionary: NSDictionary);
}
getRequest
看起來會執行以下操作:
RuutsBaseResponse
協議,就可以在任何類中使用。 generateModel
該方法應該實例化模型並將傳遞自alamoFire的Dictionary傳遞給該模型。 問題是模型,我正在努力實現上述要求。 我不斷得到:
錯誤:(22,21)'init'是該類型的成員; 使用'type(of:...)'初始化相同動態類型的新對象
我要做的就是使一個通用層足以進行服務調用,並創建一個對象/模型,該對象/模型是從alamoFire傳回的Dictionary中創建的。
您正在尋找的是如何使用泛型 :
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)
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.