GeR*_*yCh 4 generics protocols mkannotation swift
我有一个MapViewController用于在地图上显示注释.它包含一个MapPresentable类型的对象.
protocol MapPresentable {
associatedtype AnnotationElement: MKAnnotation
var annotations: [AnnotationElement] { get }
}
class MapViewController<M: MapPresentable>: UIViewController {
var mapPresentable: M!
}
Run Code Online (Sandbox Code Playgroud)
MapViewController还可以在地图上显示路由,以防mapPresentable符合RoutePresentable协议.
protocol RoutePresentable: MapPresentable {
var getRouteLocations: [CLLocation] { get }
}
Run Code Online (Sandbox Code Playgroud)
但在里面检查时 MapViewController
if let routePresentable = mapPresentable as? RoutePresentable {
showRoute(routePresentable.getRouteLocations)
}
Run Code Online (Sandbox Code Playgroud)
我有这个错误:
Protocol 'RoutePresentable' can only be used as a generic constraint because it has Self or associated type requirements
Run Code Online (Sandbox Code Playgroud)
对不起,我犯了错误.但是没有办法施放协议associated type.
希望这会有所帮助.
据我所知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)
}
Run Code Online (Sandbox Code Playgroud)
因为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)
}
Run Code Online (Sandbox Code Playgroud)