0

Here's my locationManager function, can someone please tell me why I'm getting the error: 'fatal error: unexpectedly found nil while unwrapping Optional value'?

func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {

    let userLocation: CLLocation = locations[0] as CLLocation

    CLGeocoder().reverseGeocodeLocation(userLocation) { (placemarks, error) -> Void in

    if (error != nil) {

        print(error)

    } else {

        if placemarks!.count > 0 {

            if let pm = placemarks![0] as CLPlacemark! {

            print(pm)

           self.locationButtonLabel.text = "\(pm.subLocality!),\(pm.locality!)"

           }

        }

    }

    }

}
SB2015
  • 145
  • 1
  • 1
  • 15
  • At what line is it failing? The one with `locations[0]`? Or your forcefully unwrapping of `placemarks!.count` or the next line? All these indicate unsafe code in your excerpt... – holroy Aug 07 '15 at 22:43
  • It's failing at line - self.locationButtonLabel.text = "\(pm.subLocality!),\(pm.locality!)" – SB2015 Aug 07 '15 at 22:44
  • 1
    Then your `subLocality` which you also forcefully unwrap is `nil`. You need to refactor your code and stop using the `!` when you are not positively sure it has a value. – holroy Aug 07 '15 at 22:49
  • You should also refactor the other places I commented upon in the previous comment. – holroy Aug 07 '15 at 22:51
  • Thank you, your comments helped a lot. I removed the forced unwrapping's – SB2015 Aug 07 '15 at 23:18

0 Answers0