swift - 如何使用 Do-Try-Catch 修复 "Invalid conversion from throwing function of type X to non-throwing function type Y"

标签 swift try-catch

我收到错误:从“(_) 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 block 是导致错误的关键部分,我在其中解析我的数据以进行描述。

最佳答案

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

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

关于swift - 如何使用 Do-Try-Catch 修复 "Invalid conversion from throwing function of type X to non-throwing function type Y",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57961140/

相关文章:

c# - C# 中 try/catch 的真正开销是多少?

java - 如何使 Android 猜谜游戏将猜测次数限制为 3 次尝试,之后将显示一条消息

ios - 如何将按钮触摸内部事件连接到 View Controller 方法 goBack xCode 8.2.1

swift - swift 中的 for-in 循环是如何工作的?

c# - 麻烦添加计算变量c#

loops - Powershell try catch 并重试?

c# - Try/Catch/Finally 使用加密资源

macos - 更改 View 框架大小

ios - 分配parentGroup时CNContactViewController为空

ios - 从 UITableViewCell 标识符中获取类