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

Swift 在变量上使用didSet时,如何停止nil可选值?,swift,xcode,uiviewcontroller,uikit,Swift,Xcode,Uiviewcontroller,Uikit,我通过API从ScrollViewController获取天气数据,然后设置另一个ViewController“weather”对象值。但是,当视图首次加载时,它会崩溃,因为我的TableView是在didSet和weather获取发生之前加载的 这是我的天气变量和didSet var weather: Weather! { didSet { changeLocationText(location: CLLocation(latitude:

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

这是我的天气变量和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)

如果是nil对象,则应返回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
    }

如果是nil对象,则应返回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
    }

如果天气是
nil
,您想将
cell.hourTemps
cell.hourIcons
设置为什么?您想将
cell.hourTemps
cell.hourIcons
设置为if
weather
nil