Subclassing MKCircle in Swift

I would like to subclass MKCircle (for example, MyCircle ) by adding another String property, let's call it " code ". This property does not have to be optional and permanent, so I have to set it from the initializer, right? Of course, MyCircle should also get the center coordinate and radius. These two properties are read-only, so I also need to set them through the initializer.

In the end, I need an initializer that takes 3 parameters: coordinate , radius and code . The sounds are pretty easy, but Swifts assigned and convenient inactivators and its rules give me a hard time here.

The problem is MKCircle definition:

 class MKCircle : MKShape, MKOverlay, MKAnnotation, NSObjectProtocol { convenience init(centerCoordinate coord: CLLocationCoordinate2D, radius: CLLocationDistance) convenience init(mapRect: MKMapRect) // radius will be determined from MAX(width, height) var coordinate: CLLocationCoordinate2D { get } var radius: CLLocationDistance { get } var boundingMapRect: MKMapRect { get } } 

As you can see, the MKCircle initializer, which takes coordinate and radius , is the convenience of the initializer and therefore cannot be called from the initializers of my subclass. Also, the properties are read-only, so I cannot set them from the initializers of my subclass or from the outside.

I tried many options, but it seems that the only working way is to make my code property optional, use the inherited convenience initializer to set the coordinates and radius, and after that set the code property as follows:

 class MyCircle: MKCircle { var code: String? } overlay = MyCircle(centerCoordinate: coord, radius: radius) overlay.code = code 

Did I miss something? Is there a way to define a single convenience initializer that takes 3 arguments in this case?

Thank you very much in advance!:)

+5
source share
1 answer

Not much better than your solution, just a wrapper around it:

 class MyCircle: MKCircle { var code: String! class func circleAtCenterCoordinate(coord: CLLocationCoordinate2D, radius: CLLocationDistance, code: String)->MyCircle { let circ=MyCircle(centerCoordinate: coord, radius: radius) circ.code=code return circ } } 

and use it as follows:

 let circ=MyCircle.circleAtCenterCoordinate(CLLocationCoordinate2D, radius: CLLocationDistance, code: String) 

This may be one of the annoying subclasses of Foundation classes.

+3
source

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


All Articles