Sonny Sluiter Sonny Sluiter - 5 months ago 30
Swift Question

Im trying to drop a pin but I get this error: Cannot assign value of type 'CLLocationManager' to type 'CLLocationCoordinate2D'

@IBAction func drop(sender: AnyObject)
{
let mapAnnotation = MKPointAnnotation()
mapAnnotation.coordinate = locationManager // Cannot assign value of type 'CLLocationManager' to type 'CLLocationCoordinate2D'
mapAnnotation.title = "If you want a title"
mapAnnotation.subtitle = "or subtitle"
myMap.addAnnotation(mapAnnotation)
}

Answer

As the error states, you can't assign a CLLocationManager object to a property of type CLLocationCoordinate2D.

You need to change the code to:

mapAnnotation.coordinate = locationManager.location!.coordinate

The location property can be nil due to various reasons and forced unwrapping will result in a crash. So it will be better to use safe unwrapping:

if let loc = locationManager.location
{
   mapAnnotation.coordinate = loc.coordinate
}

References:

  1. MKPointAnnotation - coordinate
  2. CLLocationManager - location
Comments