Cannot find 'ModelA' in scope using generic types

Viewed 209

I have a call api function and parameter using generic types.
And I alse craete codable data model.
Why the function parameter don't get my custom struct model and get the error Cannot find 'ModelA' in scope.
Is my T type error?
I don't know how to fix it.
Thanks.

struct ResponseHeader :Codable  {
    let returnCode : String?
    let returnMsg  : String?
}

struct ModelA :Codable {

    let responseHeader : ResponseHeader?
    let responseBody   : ResponseBody?

    struct ResponseBody: Codable {
        let name : String?
        let age  : String?
        let email: String?
    }
}

enum APIRouter: String {
    case apiA = "http://localhost:3000/ApiA"
    case apiB = "http://localhost:3000/ApiB"
    case apiC = "http://localhost:3000/ApiC"
}

class ViewController: UIViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.callApi(apiRouter: .apiA, model: ModelA) //Error. Cannot find 'ModelA' in scope
    }
    
    func callApi<T: Codable>(apiRouter: APIRouter, model: T.Type) {
        
        let urlString = URL(string: apiRouter.rawValue)
        
        if let url = urlString {
            let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
                
                guard error == nil else { return }
                
                let decoder = JSONDecoder()
                decoder.dateDecodingStrategy = .iso8601
                
                if let data = data {
                    
                    do {
                        let response = try decoder.decode(model.self, from: data)
                        print(response)
                    } catch {
                        print(error)
                    }
                    
                } else {
                    print("Error")
                }
                
            }
            
            task.resume()
        }
        
    }
    
}
1 Answers

Add self at the end.

This generic function takes as an argument an Instance Type of model so you have to pass ModelA.self.

self.callApi(apiRouter: .apiA, model: ModelA.self) //Here
Related