Failed to negotiate MKAnnotation protocol in Swift

When I try to negotiate the MKAnnotation protocol, it throws an error; my class does not conform to the MKAnnotation protocol. I am using the following code

 import MapKit import Foundation class MyAnnotation: NSObject, MKAnnotation { } 

The same is possible with Objective-C.

+5
source share
4 answers

You need to implement the following required property in calls:

 class MyAnnotation: NSObject, MKAnnotation { var myCoordinate: CLLocationCoordinate2D init(myCoordinate: CLLocationCoordinate2D) { self.myCoordinate = myCoordinate } var coordinate: CLLocationCoordinate2D { return myCoordinate } } 
+10
source

In Swift, you need to implement all the optional protocol variables and methods in order to conform to the protocol. Right now, your class is empty, which means that now it does not comply with the MKAnnotation protocol. If you look at the MKAnnotation ad:

 protocol MKAnnotation : NSObjectProtocol { // Center latitude and longitude of the annotation view. // The implementation of this property must be KVO compliant. var coordinate: CLLocationCoordinate2D { get } // Title and subtitle for use by selection UI. optional var title: String! { get } optional var subtitle: String! { get } // Called as a result of dragging an annotation view. @availability(OSX, introduced=10.9) optional func setCoordinate(newCoordinate: CLLocationCoordinate2D) } 

you can see that if you implement at least the coordinate variable, then you comply with the protocol.

+2
source

Here is a simpler version:

 class CustomAnnotation: NSObject, MKAnnotation { init(coordinate:CLLocationCoordinate2D) { self.coordinate = coordinate super.init() } var coordinate: CLLocationCoordinate2D } 

You do not need to define the optional var myCoordinate: CLLocationCoordinate2D property var myCoordinate: CLLocationCoordinate2D as the accepted answer.

+1
source

Alternatively (works in Swift 2.2, Xcode 7.3.1) (Note: Swift does not provide automatic notifications, so I throw my own.) -

 import MapKit class MyAnnotation: NSObject, MKAnnotation { // MARK: - Required KVO-compliant Property var coordinate: CLLocationCoordinate2D { willSet(newCoordinate) { let notification = NSNotification(name: "MyAnnotationWillSet", object: nil) NSNotificationCenter.defaultCenter().postNotification(notification) } didSet { let notification = NSNotification(name: "MyAnnotationDidSet", object: nil) NSNotificationCenter.defaultCenter().postNotification(notification) } } // MARK: - Required Initializer init(coordinate: CLLocationCoordinate2D) { self.coordinate = coordinate } 
0
source

Source: https://habr.com/ru/post/1216276/


All Articles