I'm implementing MapKit
into my app I have been able to display users current location. Now I'm trying to display current street name and street address onto a label which I have on my storyboard but i get this error::
Cannot convert value of type 'ViewController?' to expected argument type '_OptionalNilComparisonType' on this line of code
guard let self = self else { return }
Below is my sample code:
extension ViewController: MKMapViewDelegate {
func mapView(_ mapView: MKMapView, regionDidChangeAnimated animated: Bool) {
let center = getCenterLocation(for: mapView)
let geoCoder = CLGeocoder()
guard let previousLocation = self.previousLocation else { return }
guard center.distance(from: previousLocation) > 50 else { return }
self.previousLocation = center
geoCoder.reverseGeocodeLocation(center) { [weak self] (placemarks, error) in
guard let self = self else { return }
if let _ = error {
//TODO show alert informing the user
return
}
guard let placemark = placemarks?.first else {
//TODO Show alert informing the user
return
}
let streetNumber = placemark.subThoroughfare ?? ""
let streetName = placemark.thoroughfare ?? ""
DispatchQueue.main.async {
self?.addressLabel.text = "\(streetNumber) \(streetName)"
}
}
}
}
Update to Xcode 10 and Swift 4.2. That is the earliest version of Swift where the expression
guard let self = self else { return }
is legal.
If you can’t do that, use some other variable name on the left side of the equal sign. For example:
guard let strongself = self else { return }