Swift   发布时间:2022-04-30  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了swift – 协议只能用作通用约束大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我有@L_941_1@mapViewController用于在地图上显示注释.它包含一个 @H_992_5@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)
}

大佬总结

以上是大佬教程为你收集整理的swift – 协议只能用作通用约束全部内容,希望文章能够帮你解决swift – 协议只能用作通用约束所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。