Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

108
Vistas
Call function with completion handler

I created the function below but I'm not sure how to call it, it complains saying:

Type 'T.Type' cannot conform to 'Decodable' 

Here's how I'd like to call it:

let result = getApiData(modelToDecode: MyModel, url: "abc")

This is what I've tried:

func getApiData<T : Decodable>(modelToDecode: T.Type, url: String) -> Any? {
    // I get an error below
    fetchDataAndDecode(url: String, modelToDecode: T.Type) { result in
    }

    // temp placeholder
    return nil
}

func fetchDataAndDecode<T : Decodable>(url: String, modelToDecode: T.Type, completionHandler: @escaping (Result<T.Type, NetworkError>) -> Void) {
    guard let url = URL(string: url) else {
        completionHandler(.failure(NetworkError.badURL))
        return
    }

    AF.request(url, method: .get).validate().responseData { response in
        guard let data = response.data else {
            completionHandler(.failure(NetworkError.apiFailed))
            return
        }

        do {
            // Decode the data
            let decodedData = try JSONDecoder().decode(modelToDecode.self, from: data)
            DispatchQueue.main.async {
                completionHandler(.success(decodedData as! T.Type))
            }
        } catch(let error) {
            print("🛑 Error on afRequest(): \(error)")
        }
    }
}

How can I call it inside the class properly?

over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

Result should be Result<T, NetworkError>. No need to add modelToDecode to your method declaration. You can explicitly set the resulting type in your async call. Btw you should the completion handler as well if you fail to decode your data:

enum NetworkError: Error {
    case badURL, apiFailed, corruptedData
}

Your method should look like this:

func fetchDataAndDecode<T: Decodable>(url: String, completionHandler: @escaping (Result<T, NetworkError>) -> Void) {
    guard let url = URL(string: url) else {
        completionHandler(.failure(.badURL))
        return
    }

    AF.request(url, method: .get).validate().responseData { response in
        guard let data = response.data else {
            completionHandler(.failure(.apiFailed))
            return
        }

        do {
            let decodedData = try JSONDecoder().decode(T.self, from: data)
            DispatchQueue.main.async {
                completionHandler(.success(decodedData))
            }
        } catch {
            completionHandler(.failure(.corruptedData))
        }
    }
}

And when calling it you need to explicitly set the resulting type:

fetchDataAndDecode(url: "yourURL") { (result: Result<WhatEver, NetworkError>) in 
    // switch the result here
}
over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda