E
E
Egor Kazantsev2020-08-27 09:57:06
iOS
Egor Kazantsev, 2020-08-27 09:57:06

How to make a function as a parameter to which to pass the class that is required to work inside the function?

class func getData(
        Id: Int,
        completion: @escaping (_ response: DataResponse<MapFeatureCard>) -> Void)
    {
        let urlPath  = "https://site.ru/api/v11/superobjects/"+String(Id)
        Alamofire.request(urlPath)
            .validate()
            .cache(maxAge: 60, isPrivate: false, ignoreServer: true)
            .responseObject { (response: DataResponse<MapFeatureCard>) in
                completion(response)
        }
    }

As you can see, there is nothing overly complicated. But here the response from JSON is mapped into a dictionary of DataResponse structures.
But I would like to specify in the getData parameters the type that will be mapped and so that the default would be DataResponse (so that the existing code is not broken)
Something like this I want:
class func getData(
        Id: Int,
        RespType: Type = DataResponse<MapFeatureCard>, 
        completion: @escaping (_ response: RespType) -> Void)
    {
        let urlPath  = "https://site.ru/api/v11/superobjects/"+String(Id)    
        Alamofire.request(urlPath)
            .validate()
            .cache(maxAge: 60, isPrivate: false, ignoreServer: true)
            .responseObject { (response: RespType) in
                completion(response)
        }
    }

But something doesn’t work or somehow it turns out ugly, tell me a beautiful solution

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question