Cannot force unwrap value of non-optional type 'Reachability' for swift 5

2.2k views Asked by At

I get the warning xcode 11.1 for iOS 13 (swift 5) Cannot force unwrap value of non-optional type 'Reachability' on the line let reachability = Reachability()!

I tried, if statements and try do, but none seem to work.Removing the ! gives the warning "Call can throw, but errors cannot be thrown out of a property initializer"

import Reachability

class ReachabilityDetect {

   let reachability = Reachability()!

   var dm = DataModel()

   func addObservers(datamodel: DataModel) {
       self.dm = datamodel
       NotificationCenter.default.addObserver(self, selector: #selector(reachabilityChanged(note:)), name: .reachabilityChanged, object: reachability)
       do{
           try reachability.startNotifier()
       }catch{
           Util.DLog("Reachability notifier niet te starten.")
       }
   }

   @objc func reachabilityChanged(note: Notification) {

      let reachability = note.object as! Reachability

       switch reachability.connection {
       case .wifi:
           Util.DLog("WiFi is actief")
           self.dm.dataConnectionisWifi     = true
           self.dm.dataConnectionisCellular = false
       case .cellular:
           Util.DLog("Celluar data is actief")
           self.dm.dataConnectionisWifi     = false
           self.dm.dataConnectionisCellular = true
       case .none:
           Util.DLog("geen celluar of wifi data actief")
           self.dm.dataConnectionisWifi     = false
           self.dm.dataConnectionisCellular = false
       default: break
       }
   }

}
1

There are 1 answers

0
John Codeos On BEST ANSWER

I had the same problem.

Instead of

let reachability = Reachability()!

use this

let reachability = try! Reachability()