Unexpected non-void value in void function

I'm getting this error when I run the following code:

func execute() -> Dictionary<String, String> {
        let task = self.session.dataTask(with: request) { (data, response, error) in
            
            if error == nil && data != nil {
                do {
                    let dictionary = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? [String:Any]
                    return dictionary
                } catch {
                    print("There was an error parsing the JSON response.")
                }
            }
        }
        task.resume()
    }

The error is:
Unexpected non-void return value in void function

But it is not a void function, I have specified that it will return a dictionary!

Any help is appreciated!!

The dataTask completion handler returns Void, hence the error. Your code will not work as expected anyway, as it returns synchronously, where as dataTask works in an asynchronous fashion. So, you need to change your method to return the dictionary asynchronously. You can do this by adding a completion handler to your execute method that gives you a Result containing either a [String: Any] or an error (you can define your own errors in an enum for convenience) once the dataTask finishes.

enum NetworkError: Error {
    case networkError(Error)
    case noDataReturned
    case jsonParsingError(Error)
    case jsonCastingError
}

func execute(completion: @escaping (Result<Dictionary<String, Any>, NetworkError>) -> Void) {
    let task = session.dataTask(with: request) { (data, response, error) in
        if let error = error {
            completion(.failure(.networkError(error)))
            return
        }
        
        guard let data = data else {
            completion(.failure(.noDataReturned))
            return
        }
        
        do {
            let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers)
            guard let jsonDict = json as? [String: Any] else {
                completion(.failure(.jsonCastingError))
                return
            }
            completion(.success(jsonDict))
        } catch {
            completion(.failure(.jsonParsingError(error)))
        }
    }
    task.resume()
}