1

I am trying to cast a variable by the name of annotation that is of type MKPointAnnotation (and is inside of a mapview function) to the type of CustomPointAnnotation, which is a class I created that extends from MKPointAnnotation.

Here is the line of code that does this:

let ca = annotation as! CustomPointAnnotation

And here is the implementation of CustomPointAnnotation:

class CustomPointAnnotation: MKPointAnnotation {
    var image = UIImage()
}

But when I do this I get a runtime error on the first line shown here (let ca = ....) that says:

"Could not cast value of type 'NSKVONotifying_MKPointAnnotation' (0x7ff93d91fea0) to 'ParseStarterProject_Swift.CustomPointAnnotation' (0x1056c1f00)."

I would really appreciate your help, thanks.

Image of the line that the error occurs on: enter image description here Image of the error in the console: enter image description here

This is the whole mapview method where the error takes place. Annotation is defined as an MKAnnotation by the funtion.

func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView? {
    if annotation is MKUserLocation {
        return nil
    }

    let identifier = "MyCustomAnnotation"
    var annotationView = mapView.dequeueReusableAnnotationViewWithIdentifier(identifier)
    if annotationView == nil {
        annotationView = MKAnnotationView(annotation: annotation, reuseIdentifier: identifier)
        annotationView?.canShowCallout = true

        annotationView!.image = UIImage(named: "RaceCarMan3.png")

    } else {
        annotationView!.annotation = annotation
    }

    let ca = annotation as! CustomPointAnnotation

    configureDetailView(annotationView!, carImage: ca.imageName)

    return annotationView
}

func configureDetailView(annotationView: MKAnnotationView, carImage: UIImage) {
    annotationView.detailCalloutAccessoryView = UIImageView(image: carImage)
}
Igor Drozdov
  • 14,690
  • 5
  • 37
  • 53

0 Answers0