swift4mkpolygon

What is the designated initializer for a MKPolygon in Swift4?


I'm trying to set up a class that inherits from MKPolygon as below, but the compiler rejects my call to super.init() with the following error message:

Must call a designated initializer of the superclass 'MKPolygon'

What is the designated initializer for MKPolygon?

Following the advice of this answer and this one, I've scoured the class documentation. There are four initializers available but all of them are declared as Convenience Initializers.

I'm fairly new to Swift so I'm sure there's something simple I'm missing.

My subclass implementation is below, in case that helps.

import MapKit
import UIKit

class AudioGuideRegionAnnotation: MKPolygon {

    // MARK: - Properties
    let color: UIColor
    let image: UIImage?

    // MARK: - Initializers
    init(region: AudioGuideRegion) {
        var locations = region.locations
        super.init(coordinates: &locations, count: locations.count) // <-- rejected with "Must call a designated initializer of the superclass 'MKPolygon'"
        self.title = region.title
        self.subtitle = "\(Int(round(Double(region.duration / 60)))) minutes"
        self.color = .black
        self.image = region.images.first?.image
        super.init()
    }
}

Solution

  • The real answer to this specific issue is that you can subclass them, but your subclass must not require using its own initializer. Instead you must continue to use the convenience initializers in the super classes. Those initializers must be called otherwise MapKit won't render the data.

    For example with MKPolyline:

    let mine = MyPolyline(coordinates: c, count c.count)
    mine.other = ...
    mine.foobar = ...
    
    class MyPolyline: MKPolyline {
        var foobar: [Int] = []
        var other: [Double] = []
    }
    

    You might think you could add your own initializer and simply override methods like points and pointCount (similar to what you would for NSString for example), but MapKit still won't render the data unless its own "convenience"-marked initializers were called.