Home > front end >  Return MyRеsults from result: Result<[MyResults], Error>?
Return MyRеsults from result: Result<[MyResults], Error>?

Time:12-13

After trying to fetch all pending favors, I want to save the data in a variable and somehow print it in the table view. Still not sure how to do it, but currently I cant "save" MyResults in a variable to return? Can someone please help me? and also, Ive tried searching but cant find what type of data structure is (Result<T, Error>).

  extension URLSession {
  func fetchData<T: Decodable>(for url: URL, completion: @escaping (Result<T, Error>) -> Void) {
    self.dataTask(with: url) { (data, response, error) in
      if let error = error {
        completion(.failure(error))
      }

      if let data = data {
        do {
          let object = try JSONDecoder().decode(T.self, from: data)
          completion(.success(object))
        } catch let decoderError {
          completion(.failure(decoderError))
        }
      }
    }.resume()
  }
}

func fetchAllFavor()->MyResults
{
    let url = URL(string: get_all_pending_favors_url)!
      URLSession.shared.fetchData(for: url) { (result: Result<[MyResults], Error>) in
        switch result {
        case .success(let MyResults):
       
        break
          // A list of todos!
        case .failure(let error):
            break
          // A failure, please handle
        default:
            print("unknown")
      }
    }
}

CodePudding user response:

This sort of question comes up all the time. You can't return a result from an async function. An async function like dataTask(with:) or your fetchData() function takes a completion handler, which is a closure that it calls once the results are available.

Your should rewrite your fetchAllFavor() function following a similar pattern:

func fetchAllFavor(completion: @escaping (Result<MyResults,Error>) -> Void) {
    let url = URL(string: get_all_pending_favors_url)!
    URLSession.shared.fetchData(for: url) { (result) in
        completion(result)
    }
}



CodePudding user response:

Use alamofire as it is much better

  • Related