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

Hi! Does anyone know how to fix this error? I got the source code from:

"Call can throw, but it is not marked with 'try' and the error is not handled" was next to self.reachability = Reachability.init()

class DataViewController: UIViewController {

@IBOutlet weak var lblStatus: UILabel!

var reachability: Reachability?

override func viewDidLoad() {
    // Do any additional setup after loading the view, typically from a nib.
    self.reachability = Reachability.init()
    if ((self.reachability!.connection) != .unavailable)
        print("Internet Available")
        lblStatus.text! = "Internet Available"
    } else
        print ("internet not Available")
        lblStatus.text! = "Internet not Available"

Where is the Reachability type defined? Maybe it has a throw-ing default initializer?

This is what I have in Reachability.swift, it gives me the same error for guard let self = self else { return }

func notifyReachabilityChanged() {
let notify = { [weak self] in
guard let self = self else { return }
self.connection != .unavailable ? self.whenReachable?(self) : self.whenUnreachable?(self) .reachabilityChanged, object: self)

Try this line instead:

self.reachability = try? Reachability.init()

The issue is that the initializer you are using is marked with ‘throws’ which means that it can throw an exception when it encounters a problem. (Search for Swift Exceptions for more info.) Swift forces you to acknowledge that by marking your call with a try. By using “try?” here, we are telling it: “Try to run the function, but if it fails and throws an exception, just return nil instead.”

Terms of Service

Privacy Policy

Cookie Policy