How are subclasses of a class that has no assigned initializers?

I'm trying to subclass MKPolyline. However, the problem is that MKPolylinethere are no designated initializers. Here is what I tried to do:

import MapKit

class MyPolyline: MKPolyline {
    let locations: [Location]

    init(locations: [Location]) {
        self.locations = locations

        var coordinates: [CLLocationCoordinate2D] = []
        for location in locations {
            coordinates.append(location.coordinate)
        }
        super.init(coordinates: coordinates, count: coordinates.count)
    }
}

But I get an error Must call a designated initializer of the superclass 'MKPolyline'when calling super.init. As far as I know, MKPolylineit has no designated initializers.

What should I do? How can I subclass a class that has no assigned initializers?

+4
source share
1 answer

Assigned Initializers

, , , . Swift , Swift .

, . . , init , , , .

, MKPolyline init, . , .

:

Swift , , , .

, , , MKPolyline , . , Swift , init init . - init . , Swift .

inits - , , inits . , , . init, init, init, .

, MKPolyline, , . , , , .

, init, Location, init MKPolyline .

- , , . , locations , getCoordinates.

:

extension MKPolyline {

    var locations: [Location] {
        guard pointCount > 0 else { return [] }

        let defaultCoordinate = CLLocationCoordinate2D(latitude: 0.0, longitude: 0.0)
        var coordinates = [CLLocationCoordinate2D](repeating: defaultCoordinate, count: pointCount)
        getCoordinates(&coordinates, range: NSRange(location: 0, length: pointCount))

        // Assuming Location has an init that takes in a coordinate:
        return coordinates.map({ Location(coordinate: $0) })
    }

    convenience init(locations: [Location]) {

        let coordinates = locations.map({ $0.coordinate })

        self.init(coordinates: coordinates, count: coordinates.count)
    }

}

. init, , , , init self, . map Location.

, locations, getCoordinates . , , , , getCoordinates Objective-C UnsafeMutablePointer Swift. CLLocationCoordinate2D , getCoordinates, , range. & coordinates Swift, inout- .

locations , Location, , , , , .

Wrapper

"Swifty" , , , . , , MKPolyline:

class MyPolyline {

    let underlyingPolyline: MKPolyline

    let locations: [Location]

    init(locations: [Location]) {
        self.locations = locations

        let coordinates = locations.map { $0.coordinate }
        self.underlyingPolyline = MKPolyline(coordinates: coordinates, count: coordinates.count)
    }

}

, , MyPolyline MKPolyline, myPolyline.underlyingPolyline . , , - , , MKPolyline, , , , Apple.

+2

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


All Articles