0

I've used the debugger in XCode and noticed that I'm not returning a value for the following. I've contained the error to this section of the code by debugging all other parts first.

extension Article {
    
    static var previewData: NewsAPIResponse = {
        var temp : NewsAPIResponse = NewsAPIResponse(content: [])
        let url = URL(string: "REPLACED WITH MY_API_KEY")
        
        var request = URLRequest(url: url!)

        request.addValue("application/json", forHTTPHeaderField: "Accept")
        let task = URLSession.shared.dataTask(with: url!) { data, response, error in
            guard error == nil else {
                print(error!)
                return
            }
            guard let data = data else {
                print("Data is empty")
                return
            }
            let jsonDecoder = JSONDecoder()
            let dateFormatter = DateFormatter()
            dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
            jsonDecoder.dateDecodingStrategy = .formatted(dateFormatter)

            temp = try!jsonDecoder.decode(NewsAPIResponse.self, from: data)
            print(temp)
            //putting the return statement here throws an error
        }
        print(temp)
        return temp ?? NewsAPIResponse(content: [])
        task.resume()
    }()
}
  • To illustrate the asynchrone: `print(temp)` => `print("Inside closure: \(temp)")`, and just before the `return temp ?? ...`: `print("Outside closure: \(temp)")`, and see which one is outputted first in console, and that's not the other you think. – Larme Apr 05 '22 at 12:28
  • Yep I lose the value of temp after the close, but I don't understand why since temp is outside the closure itself. – Daniel Jeong Apr 05 '22 at 12:39
  • Also, I have the problem of task.resume() – Daniel Jeong Apr 05 '22 at 12:40
  • It's not about losing the value, it's about timing. `temp = ` is called AFTER, so it's nil. – Larme Apr 05 '22 at 12:40
  • What do you mean? I edited the code, and the temp outside the closure is empty, but I can't have a non-void return statement inside the loop. – Daniel Jeong Apr 05 '22 at 12:44

0 Answers0