8

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

In the end I need an initializer that takes 3 parameters: coordinate, radius and code. Sounds pretty easy but Swifts designated and convenience initalizers and its rules are giving me a hard time here.

Problem is the definition of MKCircle:

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 initializer of MKCircle that takes coordinate and radius is a convenience initalizer and therefore not callable from initializers of my subclass. Also the properties are read-only so I cannot set them from initializers of my subclass or from outside.

I've tried a lot of variations but it seems that the only working way is to make my code property an optional, use the inherited convenience initializer to set coordinate and radius and set the code property afterwards, like this:

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?

Many thanks in advance! :)

  • This doesn't answer your main question but: MKCircle already has two string properties that it inherits from MKShape: `title` and `subtitle`. –  Sep 30 '14 at 11:30

2 Answers2

3

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 like this:

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

This can be one of the annoying thing of subclassing Foundation classes.

0
class MyCircle: MKCircle {

    private(set) var code: String?

    private override init() {
        super.init()
    }

    static func Instance(center: CLLocationCoordinate2D, radius: CLLocationDistance, code: String?) -> MyCircle {
        let instance = MyCircle(center: center, radius: radius)
        instance.code = code
        return instance
    }
}
zyxman
  • 72
  • 5