adauguet adauguet - 2 years ago 202
Swift Question

MKAnnotation protocol inheritance

I need to create a protocol that inherits from MKAnnotation:

protocol Annotable: MKAnnotation {

class Annotation: NSObject, Annotable {
var title: String?
var coordinate: CLLocationCoordinate2D

init(title: String, coordinate: CLLocationCoordinate2D) {
self.title = title
self.coordinate = coordinate

There is no problem when I add a couple of those annotations to the mapView.

mapView.addAnnotations([Annotation(...), Annotation(...), ...]

But when I try to loop on the annotations collection, the app crashes at runtime:

for annotation in mapView.annotations { // fatal error: NSArray element failed to match the Swift Array Element type

My question is simple: why?

Since Annotation conforms to MKAnnotation, it is no surprise that they can be added to the mapView. So why could not we retrieve them?

Thanks a lot!

Rob Rob
Answer Source

You can resolve this by declaring your protocol as an @objc protocol:

@objc protocol Annotable: MKAnnotation {
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download