I am creating an app that fetches stock data from Alpha Vantage and displays it, as a first attempt at Swift (I usually develop in JS).
More precisely, I have a table view, and each cell has the following labels:
- "Open" price label
- "High" price label
- "Low" price label
- "Close" price label
- "Volume" label
This is the custom class I'm using for the cell.
import UIKit
class StockChoiceCell: UITableViewCell {
@IBOutlet weak var openPriceLabel: UILabel!
@IBOutlet weak var highPriceLabel: UILabel!
@IBOutlet weak var lowPriceLabel: UILabel!
@IBOutlet weak var closePriceLabel: UILabel!
@IBOutlet weak var volumeLabel: UILabel!
}
I have an asynchronous function that successfully retrieves the desired data from Alpha Vantage and returns [DataPoint]
, where DataPoint is a struct that contains the open, high, low and close prices, as well as the volume. I say successful, as I use the function in another facet of the app without issues.
That function resembles:
func retrieveDataFromAPI (tic: String, completion: @escaping ([DataPoint])->()) {
// Fetch stuff
// Pack it under the DataPoint structure
// ...
completion(arrayOfDataPoints)
}
Here is the issue.
Due to the asynchronous nature of the function, I do not know how to make the application "wait" for the data fetching to complete before running:
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! StockChoiceCell
// ... Setting stuff, etc.
return cell
}
I searched online, trying primarily the following two posts, as one of my attempts consisted of nesting the asynchronous function within another synchronous function:
If this were JS, I'd immediately use a Promise. But Swift is new to me, and I am still exploring how asynchronous functions work in the language.
Thank you!
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…