Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

102
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
ยฉ 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!