The protocol can only be used as a general restriction.

I have a MapViewController to represent annotations on a map. It contains an object of type MapPresentable.

protocol MapPresentable {
    associatedtype AnnotationElement: MKAnnotation
    var annotations: [AnnotationElement] { get }
}

class MapViewController<M: MapPresentable>: UIViewController {
    var mapPresentable: M!
}

MapViewController can also display a route on a map if it mapPresentableconforms to the RoutePresentable protocol.

protocol RoutePresentable: MapPresentable {
    var getRouteLocations: [CLLocation] { get }
}

But when checking inside MapViewController

if let routePresentable = mapPresentable as? RoutePresentable {
    showRoute(routePresentable.getRouteLocations)
}

I got this error:

Protocol 'RoutePresentable' can only be used as a generic constraint because it has Self or associated type requirements
+4
source share
1 answer

Update

Sorry, I'm making mistakes. But there is no way to pass the protocol using associated type.

Hope this helps.

As you know, routePresentable.getRouteLocationsit has nothing to do with the protocol MapPresentable.

So, you can divide RoutePresentableinto two protocols:

protocol MapPresentable {
    associatedtype AnnotationElement: MKAnnotation
    var annotations: [AnnotationElement] { get }
}

class MapViewController<M: MapPresentable>: UIViewController {
    var mapPresentable: M!

}

protocol RoutePresentable: MapPresentable, CanGetRouteLocations {}

protocol CanGetRouteLocations {
    var getRouteLocations: [CLLocation] { get }
}


if let routePresentable = mapPresentable as? CanGetRouteLocations {
    showRoute(routePresentable.getRouteLocations)
}

Original

routePresentable.annotations ,

associatedtype AnnotationElement: MKAnnotation.

:

struct MapPresentable<AnnotationElement: MKAnnotation> {
    var annotations: [AnnotationElement] = []
}

struct RoutePresentable<AnnotationElement: MKAnnotation> {
    var mapPresentable: MapPresentable<AnnotationElement>
    var getRouteLocations: [CLLocation] = []
}

class MapViewController<AnnotationElement: MKAnnotation>: UIViewController {

    var mapPresentable: MapPresentable<AnnotationElement>!

}

if let routePresentable = mapPresentable as? RoutePresentable<MKAnnotation> {
    showRoute(routePresentable.getRouteLocations)
}
+4

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


All Articles