在变量上使用 didSet 时如何停止 nil 可选值?

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

我正在通过 API 从 ScrollViewController 获取天气数据,然后设置另一个 ViewControllers "Weather" 对象值。但是,当视图首次加载时,它崩溃了,因为我的 TableView 在 didSet 和天气获取发生之前加载。

这是我的天气变量和 didSet

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

这是我通过 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

这是我在 ScrollViewController 中获取天气信息后更新天气信息的地方

func updateViewControllers() {
    mainVC.weather = weather
}

错误(致命错误:在隐式展开可选值时意外发现 nil)

如果没有对象,您应该 return 0 个部分或 0 个单元格

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

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