Swift 2.1 - 调用可以抛出,但是没有用'try'标记,错误没有被处理

Swift 2.1 - Call can throw, but it is not marked with 'try' and the error is not handled

我在使用以下代码时遇到错误,我该如何解决?

'调用可以抛出,但是没有标明'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

    }

如果查看 example,则需要用 try 包装调用。

let reachability = try Reachability.reachabilityForInternetConnection()

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

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

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