协议只能用作通用约束

4

我有一个MapViewController用于在地图上展示标注。它包含一个类型为MapPresentable的对象。

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

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

如果mapPresentable符合RoutePresentable协议,MapViewController也可以在地图上呈现路线。

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

但是,当在MapViewController内进行检查时

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

我得到了这个错误:
Protocol 'RoutePresentable' can only be used as a generic constraint because it has Self or associated type requirements
1个回答

5

已更新

抱歉,我犯了错误。但是没有办法使用关联类型转换协议。

希望这能有所帮助。

据我所知,routePresentable.getRouteLocations与协议MapPresentable无关。

因此,您可以将RoutePresentable分为两个协议:

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

翻译

因为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)
}

谢谢你的回答!不幸的是,我没有理解你的通用解决方案。MapPresentable和RoutePresentable必须是协议(实际上有符合它们的类型)。那么强制转换语句会如何工作呢?在这种情况下,MapPresentable和RoutePresentable是不同的结构体。 - GeRyCh
太好了!你的更新帮助解决了类型转换问题!谢谢! - GeRyCh

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接