【问题标题】:How to fix "Invalid conversion from throwing function of type X to non-throwing function type Y" with Do-Try-Catch如何使用 Do-Try-Catch 修复“从 X 类型的抛出函数到 Y 类型的非抛出函数的无效转换”
【发布时间】:2019-09-16 16:40:09
【问题描述】:

我收到错误:从“(_) throws -> ()”类型的抛出函数到非抛出函数类型“(Either) -> Void”的无效转换

do {weatherApi.weather(with: weatherEndpoint) { (either) in之后上线

class WeatherTableViewController: UITableViewController {

    var cellViewModels = [WeatherCellViewModel]()

    override func viewDidLoad() {
        super.viewDidLoad()
        let weatherApi = WeatherAPIClient()
        let weatherEndpoint = WeatherEndpoint.fiveDayForecast(city: "Atlanta", country: "us")

        do {
            weatherApi.weather(with: weatherEndpoint) { (either) in
            switch either {
                case .value(let Weather):
                    print("Made it")
                    print(Weather)
                    let data = try Weather.map {
                        $0.weather.map {
                            WeatherCellViewModel(description: $0.description)
                        }
                    }
                    print("data")
                    print(data)

                    DispatchQueue.main.async {
                        self.tableView.reloadData()
                    }
                case .error(let error):
                    print(error)
                }
            }
        } catch {
            print("weather endpoint error")
        }
    }

我在最初遇到相同的错误并查看类似问题的答案后添加了 do try catch,但它并没有解决它。 try 块是导致错误的关键部分,我正在解析我的数据以获取描述。

【问题讨论】:

    标签: swift try-catch


    【解决方案1】:

    do-catch 当前位于包含 try 语句的闭包之外。

    您需要将do-catch 移动到闭包中。错误是因为 weather 期望的闭包不会抛出,但它会继续抛出。

    【讨论】:

      【解决方案2】:

      你想从闭包中抛出,这是不可能的。所以你需要将do-catch 放入闭包中

      试试这个方法:

          do {
                let data = try Weather.map {
                          $0.weather.map {
                              WeatherCellViewModel(description: $0.description)
                   }
               }
          } catch let error as NSError {
              print(error)
          }
      

      【讨论】:

        猜你喜欢
        • 2017-12-04
        • 1970-01-01
        • 2018-12-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多