Subclassing MKCircle in Swift

流过昼夜 提交于 2021-01-27 04:06:12

问题


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! :)


回答1:


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.




回答2:


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
    }
}


来源:https://stackoverflow.com/questions/26117350/subclassing-mkcircle-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!