Search code examples
swiftxcodeuiviewcontrolleruikit

How can I stop nil optional value when using didSet on a variable?


I am fetching weather data via an API from a ScrollViewController and then setting another ViewControllers "Weather" Object value. However, when the view first loads, it crashes because my TableView is loading before the didSet and weather fetch occurs.

Here is my weather variable with the didSet

var weather: Weather! {
        didSet {
            changeLocationText(location: CLLocation(latitude: 
        weather.currentLatitude, longitude: 
        weather.currentLongitude))
        tableView.reloadData()
    }
}

Here is where I access weather via tableView

let cell = tableView.dequeueReusableCell(withIdentifier: "hourlyCell", for: indexPath) as! HourlyCell
cell.hourTemps = weather.hourTemps //Error here
cell.hourIcons = weather.hourIcons
cell.collectionView.reloadData()
return cell

Here is where I am updating weather after it is fetched in my ScrollViewController

func updateViewControllers() {
    mainVC.weather = weather
}

Error (Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value)


Solution

  • You should either return 0 sections or 0 cells in case of nil object

        func numberOfSections(in tableView: UITableView) -> Int {
          return weather == nil ? 0 : 1
        }
    
        func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
          return weather == nil ? 0 : 1
        }