簡體   English   中英

將遵循給定協議的類傳遞給方法,然后使用swift實例化該類

[英]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看起來會執行以下操作:

  1. 只要符合RuutsBaseResponse協議,就可以在任何類中使用。
  2. 使用傳遞給它的參數使用alamoFire進行服務調用。
  3. 服務調用完成后,alamoFire將調用generateModel方法。
  4. 當它調用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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM