Search code examples
swiftinheritanceoverridingmember

Overriding with a stored property


I extended the MKPointAnnotation class this way:

class CustomPointAnnotation: MKPointAnnotation{

    let eventID: Int
    let coords: CLLocationCoordinate2D
    var title: String? // error here
    let location:String

    init(eventID:Int, coords:CLLocationCoordinate2D, location:String, title:String?) {

        self.eventID = eventID
        self.coords = coords
        self.title = title
        self.location = location

        super.init()
    }
}

I get an error:

Cannot override with a stored property 'title' 

(I suppose I'd get the same error if I renamed the member coords to coordinate).

So, I tried the following:

private var _title:String?

override var title: String? {
        get { return _title }
        set { _title = newValue }
    }

but, as I add self.title = title in the body of the init I get:

'self' used in property access 'title' before 'super.init' call

If I move super.init() above, I get two kinds of error:

  1. Property 'self.eventID' not initialized at super.init call (1 error)
  2. Immutable value 'self.coords' may only be initialized once (repeated for every property)

What's the right way to declare the title property? Is there any possibility to override it? I found many questions about this topic, but no example with extending a built-in class. Any help is appreciated


Solution

  • Why do you need to redeclare var title: String? again? by subclassing MKPointAnnotation you already have access to title. (same thing goes for coords).

    You can just set title, after super.init()

    init(eventID: Int, coords: CLLocationCoordinate2D, location: String, title: String?) {
    
            self.eventID = eventID
            self.coords = coords
            self.location = location
    
            super.init()
            self.title = title
        }
    

    If you want to rename coordiante to coords for your readability purposes, I suggest to use an extension:

    extension CustomPointAnnotation {
        var coords: CLLocationCoordinate2D {
            get { return coordinate }
            set { coordinate = newValue }
        }
    }
    

    And assign it after super.init() just like title.