I am trying to append array(simple task I know) but for some reason my array is empty. No matter what I do. This is what I do:
I want to calculate the total balance(I should do amount * price and then sum them up).
So I thought I would make array of balances and then sum them up but the array is empty:
func getBalances(completion: @escaping (_ balancesArray: [Double])->()){
var balancesArray = [Double]()
for f in portfolioArray{
getPrice(for: f.name!, in: "EUR", completion: { (price) in
balancesArray.append(f.amount * price)
//!!!!!!If I print here the array, it is full!!!!!!
})
}
completion(balancesArray)
}
This is the getPrice function(it returns the price, I tested):
func getPrice(for crypto: String, in fiat: String, completion: @escaping (_ price: Double)->()){
API.getCryptoRates(cryptoSymbol: crypto, fiatSymbol: fiat) { (error, response: [CurrencyResponse]?) in
if error == nil{
if let prices = response{
guard let p = Double(prices[0].price) else { return }
completion(p)
}
}
}
}
So my question is, why is it empty? If I am correct then the completion should have the filled array. And there shouldn't be any thread problems.
Can somebody please lead me to the right track. Any response is appreciated!