最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

swift - Struggling to implement specific variables into a table view cell because of user default values missing - Stack Overflo

programmeradmin4浏览0评论

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?

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?

Share Improve this question edited Mar 21 at 14:37 HangarRash 15.1k5 gold badges20 silver badges55 bronze badges asked Mar 21 at 13:32 Train LoverTrain Lover 199 bronze badges 4
  • Maybe use viewDidLoad or similar to set the content of the WeatherForecastCells array. – Joakim Danielson Commented Mar 21 at 13:55
  • @JoakimDanielson I like that idea, but how would I access the variable outside of the viewDidLoad()? it would be exclusive to that function wouldn't it? – Train Lover Commented Mar 21 at 13:56
  • You still declare it as a type property but initialise it to an empty array and then you add the values in viewDidLoad – Joakim Danielson Commented Mar 21 at 14:08
  • @JoakimDanielson your onto something... I put the data in the didUpdateWeather() function because I am unable to access the properties that I'm looking for in viewDidLoad() (because they are only available in the DidUpdateWeather() function.) DO you know how I can trigger the extension code after the DidUpdateWeather() function does it's thing, not simply when the app loads in? – Train Lover Commented Mar 21 at 14:27
Add a comment  | 

2 Answers 2

Reset to default 1

The error is pretty clear. It means you're attempting to get date1ForTableView before self is available. You can take one of the following approaches:

  1. Using lazy to ensure that the initial value is valid before self:
private lazy var WeatherForecastCells: [WeatherCell] = [
    WeatherCell(image: "", date: date1ForTableView.string(forKey: "Date1")!, low: "18°", high: "31°"),
    ...
]
  1. Because your date1ForTableView is simply a get for UserDefaults.standard, you may want to replace it with a computed property:
private var date1ForTableView: UserDefaults {
    .standard
}

private var WeatherForecastCells: [WeatherCell] = [
    WeatherCell(
        image: "", 
        date: date1ForTableView.string(forKey: "Date1")!, //<- ✅ here
        low: "18°", 
        high: "31°"),
    ...
]

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°"),
      ...
   ]

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论