function doesnt return a value

I'm new at Swift and that's why i need your help. So I have a function which should send request and return a value

func getAnswer() -> String? {
        var  answer: String?
        guard let url = URL(string: "https://8ball.delegator.com/magic/JSON/_") else { return nil }
        
        URLSession.shared.dataTask(with: url) { data, response, error in
            guard let data = data, error == nil else {
                return
            }
            
            guard let response = response as? HTTPURLResponse else { return }
            
            guard response.statusCode == 200 else { return }
            
            do {
                let model = try JSONDecoder().decode(Answer.self, from: data)
                
                DispatchQueue.main.async {
                    answer = model.magic.answer
                }
            } catch let error {
                fatalError(error.localizedDescription)
            }
            
        }.resume()
        
        return answer
    }

but it always returns nil. I suppose problem is here

DispatchQueue.main.async {
    answer = model.magic.answer
}

How can I resolve it?

The function cannot return the value retrieved by your dataTask, as the function returns before the dataTask finishes.
The dataTask completion should set some value in the wider environment, or itself call a passed-in completion closure.

or itself call a passed-in completion closure.

Yep. Or, if you prefer to maintain a more linear style, you could adopt Swift concurrency. For more on this, see our Meet Swift Concurrency page.

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"

function doesnt return a value
 
 
Q