协议只能用作通用约束 [英] Protocol can only be used as a generic constraint
本文介绍了协议只能用作通用约束的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个用于在地图上显示注释的MapViewController。它包含一个类型为MapPresentable的
对象。
I have a MapViewController for presenting annotations on 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也可以在
MapViewController can also present route on map in case mapPresentable
conforms to RoutePresentable protocol.
protocol RoutePresentable: MapPresentable {
var getRouteLocations: [CLLocation] { get }
}
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
推荐答案
更新
对不起,我犯了错误。但是没有办法用关联类型
来转换协议。
希望这会有所帮助。
因为我知道 routePresentable.getRouteLocations
与协议 MapPresentable
因此,您可以将 RoutePresentable
分成两个协议:
So you can divide RoutePresentable
to two protocol:
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)
}
这篇关于协议只能用作通用约束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文