I have been working to make a weather feature in my app, which takes API data from Visual Crossing.
The issue is that the data is extracted into my app in a seperate function then that which sets my table view cells in my app.
Here is the code I have so far:
let date1ForTableView = UserDefaults.standard
func didUpdateWeather(weather: WeatherModel) {
DispatchQueue.main.async {
self.date1ForTableView.set(weather.datetime1, forKey: "Date1")
...
}
...
var WeatherForecastCells: [WeatherCell] = [
WeatherCell(image: "", date: date1ForTableView.string(forKey: "Date1")!, low: "18°", high: "31°"),
...
]
...
extension WeatherFeatures: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return WeatherForecastCells.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "WeatherCellsForWeatherFeature", for: indexPath) as! WeatherForecastTableViewCell
cell.WeatherDetails.text = "\(WeatherForecastCells[indexPath.row].date) - Low: \(WeatherForecastCells[indexPath.row].low) High: \(WeatherForecastCells[indexPath.row].high)"
return cell
}
}
Here is how it works: in the didUpdateWeather() function, the date is saved to a user default value. It is automatically set when the location is entered in the app. For context, we have the data.
What seems to then happen is when I try to set the value in WeatherForecastCells is I get the error "Cannot use instance member 'date1ForTableView' within property initialiser; property initialisers run before 'self' is available" How can I get rid of the above error?
The cells were hardcoded in the below code, and therefore they were only called once. I added this code into the tableView cell for row at function and it resolved the issue as it updated the variable every time the app loaded in:
var WeatherForecastCells: [WeatherCell] = [
WeatherCell(image: "", date: date1ForTableView.string(forKey: "Date1")!, low: "18°", high: "31°"),
...
]