【问题标题】:Swift 2.1 - Call can throw, but it is not marked with 'try' and the error is not handledSwift 2.1 - 调用可以抛出,但它没有用'try'标记并且错误没有被处理
【发布时间】:2016-01-25 21:13:55
【问题描述】:

以下代码出现错误,我该如何解决?

'调用可以抛出,但没有标记'try',错误未处理'

 let reachability = Reachability.reachabilityForInternetConnection() // - Error Here

        reachability.whenReachable = { reachability in
            if reachability.isReachableViaWiFi() {
                let alertController = UIAlertController(title: "Alert", message: "Reachable via WiFi", preferredStyle: .Alert)

                let defaultAction = UIAlertAction(title: "OK", style: .Default, handler: nil)
                alertController.addAction(defaultAction)

                self.presentViewController(alertController, animated: true, completion: nil)

            }
            else {
                let alertController = UIAlertController(title: "Alert", message: "Reachable via Cellular", preferredStyle: .Alert)

                let defaultAction = UIAlertAction(title: "OK", style: .Default, handler: nil)
                alertController.addAction(defaultAction)

                self.presentViewController(alertController, animated: true, completion: nil)
            }
        }
        reachability.whenUnreachable = { reachability in
            let alertController = UIAlertController(title: "Alert", message: "Not Reachable", preferredStyle: .Alert)

            let defaultAction = UIAlertAction(title: "OK", style: .Default, handler: nil)
            alertController.addAction(defaultAction)

            self.presentViewController(alertController, animated: true, completion: nil)
        }

        reachability.startNotifier() // - Error Here

    }

【问题讨论】:

  • 你看过github.com/ashleymills/Reachability.swift上的“示例 - 闭包”吗?
  • @Leo Dabus 您能否更新此问题中的以下代码,谢谢,目前出现错误。
  • @GurvierSinghDhillon 尝试先阅读 Martin R 刚刚为您发布的链接
  • @Mark R 我可以使用您提供的链接获得该方法,但是我想要在这里实现的是显示一个 AlertController,无论它们是否是互联网连接。

标签: xcode swift viewcontroller


【解决方案1】:

如果您查看example,则需要使用try 包装呼叫。

let reachability = try Reachability.reachabilityForInternetConnection()

Swift 的 try/catch 系统旨在让开发人员一目了然,这意味着您需要使用 try 关键字标记任何可以抛出的方法。

当函数抛出错误时,它会改变程序的流程,因此您可以快速识别代码中可能抛出错误的位置,这一点很重要。要识别代码中的这些位置,请在调用可能引发错误的函数、方法或初始化程序的一段代码之前编写 try 关键字(或 try?try! 变体)。

您可以在 Apple 参考资料site 阅读更多内容。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-08-24
    • 1970-01-01
    • 2016-01-24
    • 2017-11-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-21
    相关资源
    最近更新 更多