MKAnnotation协议继承

MKAnnotation protocol inheritance

我需要创建一个继承自 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
    }
}

当我向 mapView 添加几个注释时没有问题。

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

但是当我尝试在注释集合上循环时,应用程序在运行时崩溃:

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

我的问题很简单:为什么?

既然Annotation是符合MKAnnotation的,那么它们可以添加到mapView也就不足为奇了。那为什么我们不能找回它们呢?

非常感谢!

您可以通过将协议声明为 @objc 协议来解决此问题:

@objc protocol Annotable: MKAnnotation {
    ...
}