0

I am trying to understand completion handlers and @escaping.

In the code below, I am using an escaping completion on a function. However, when I call the function to assign its output to a variable it doesn’t wait for the api response. It prints out "This is the new_stock ()".

What am I missing?

I think I can do something like DispatchQueue.main.asyncAfter(deadline: .now() + 4){} to get the value but my point is there is still something I am misunderstanding with completion handlers and @escaping that is not connecting with me.

struct Stock: Codable {
  let open: Double
  let high: Double
  let low: Double
  let current: Double
  let previous_close: Double
  let name: String?
}


func getStockInfo(symbol: String, completion: @escaping (Stock) -> Stock) {
    var stock = Stock(open: 0, high: 0, low: 0, current: 0, previous_close: 0, name: "XXX")
    let urlString = "https://api.lil.software/stocks?symbol=\(symbol.uppercased())"
    guard let url = URL(string: urlString) else {
        fatalError("URL could not be constructed")
    }
    let request = URLRequest(url: url)
    URLSession.shared.dataTask(with: request) { (data, response, error) in
        if let error = error {
            fatalError("Error retieving quote: \(error.localizedDescription)")
        }
        let decoder = JSONDecoder()
        do {
            stock = try decoder.decode(Stock.self, from: data!)
            completion(stock)
            
        } catch {
            fatalError("Error decoding data \(error.localizedDescription)")
        }
    }
    .resume()
//    return stock
}

let new_stock = getStockInfo(symbol:"OTEX"){ returnedData in
    return returnedData
}

print("This is the new_stock \(new_stock)")

This example is taken from this tutorial: https://www.youtube.com/watch?v=tuHcwRe61KE. Which is helpful, but like I said this is still not clicking. Thanks in advance.

costa rica
  • 85
  • 1
  • 12
  • Don't keep yourself dealing with completion handlers, go for `async/await`. And **never** `print(error.localizedDescription)` in a `Codable` context, always `print(error)` – vadian Feb 24 '23 at 11:35

0 Answers0