-2

I am quite new to swift and I am learning to make HTTP requests from an API.

Right now I have this struct

struct CNJokesProvider  {
    let url = URL(string: "https://api.chucknorris.io/jokes/random")!

    func getRandomJoke() -> String {
        var request = URLRequest(url: url)

        request.httpMethod = "GET"

        let session = URLSession.shared

        let task = session.dataTask(with: request, completionHandler: { data, response, error -> Void in
            do {
                let json = try JSONDecoder().decode(CNJokesResponse.self, from: data!)
            } catch {
                print("\(error)")
            }
        })

        task.resume()

        //return json.value
    }
}

and you can see the declaration of the json constant. I need to get the data from the constant to return it from this getRandomJoke function. I tried to make it a struct property but I couldn't make it work.

1 Answers1

-1

You are declaring json property inside a task so it means you can't access it outside a do-catchstatement there.

Sangsom
  • 373
  • 5
  • 9