[Solved] Return struct after parsing json in Swift


I found the solution. You have to add a closure and then use it when calling the function.

func getData(symbol: String, completion: @escaping (Stock) -> Void) {


        let apiURL = "https://cloud.iexapis.com/stable/stock/\(symbol)/quote?token=\(secretToken)"
        let url = URL(string: apiURL)!

        URLSession.shared.dataTask(with: url) { (data, response, err) in

        guard let data = data else { return  }

            do {
                let json = try JSONDecoder().decode(Stock.self, from: data)
                let stockResult = Stock(symbol: json.symbol,
                                        companyName: json.companyName,
                                        latestPrice: json.latestPrice
                )

                //I want to return this Stock structure

                completionBlock(stockResult)

            } catch let jsonErr {
                print("Error serialising json: ", jsonErr)
            }
        }.resume()

    }

then in the main you call

getData(symbol: "aapl") {(output) in
            print(output)
}

solved Return struct after parsing json in Swift