Using a custom MKPointAnnotation

I've created a custom MKPointAnnotation class that simply holds a little extra data.


import UIKit
import MapKit

class MyCustomPointAnnotation: MKPointAnnotation {
     var customVariable: Bool!

     init(customVariable: Bool) {
          self.customVariable = customVariable
     }
}


The following code works great:


func addAnnotation() {
     let annotation = MyCustomPointAnnotation(customVariable: true)
     annotation.coordinate = aCoordinate
     annotation.title = "My Title"

     map.addAnnotation(annotation)
}


However, I'm not sure how to make that annotation appear as my custom class in a function that gets called when the annotations are being created.


func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
     // Works
     print(annotation.title)

     //Doesn't work and the variable isn't even available in the code hint
     print(annotation.customVariable)
}


The variable annotation that's being pased as an MKAnnotation is maybe stripping my custom class from the annotation? How can I preserve my class as it's passed to other functions?


Thanks!

Replies

In your last code example, the annotation parameter is of the type MKAnnotation. MKAnnotation is a protocol that is implemented by MKPointAnnotation (and also your custom subclass MyCustomPointAnnotation, implicitly). In other words, every instance of your subclass MyCustomPointAnnotation conforms to MKAnnotation, but not every MKAnnotation is an instance of MyCustomPointAnnotation. (Real world analogy: Every apple is a fruit, but not every fruit is an apple.)


To use your custom variable, you must downcast the MKAnnotation entity to your custom class. In Swift, here is the safest way to do so:

if let customAnnotation = annotation as? MyCustomPointAnnotation {
    print(customAnnotation.customVariable)
}


The code above means the following: If annotation is an instance of the MyCustomPointAnnotation class, create a variable called customAnnotation of that type.


Click the Apple docs links above for more details, or feel free to ask for clarification. 🙂