加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

swift – 协议只能用作通用约束

发布时间:2020-12-14 04:37:55 所属栏目:百科 来源:网络整理
导读:我有一个MapViewController用于在地图上显示注释.它包含一个 MapPresentable类型的对象. protocol MapPresentable { associatedtype AnnotationElement: MKAnnotation var annotations: [AnnotationElement] { get }}class MapViewControllerM: MapPresentab
我有一个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

解决方法

更新

对不起,我犯了错误.但是没有办法使用相关类型转换协议.

希望这会有所帮助.

据我所知,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的类型未提供,

您可以删除关联类型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)
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读