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

swift – 协议只能用作通用约束,第1张

概述我有一个MapViewController用于在地图上显示注释.它包含一个 MapPresentable类型的对象. protocol MapPresentable { associatedtype AnnotationElement: MKAnnotation var annotations: [AnnotationElement] { get }}class MapVie 我有一个MapVIEwController用于在地图上显示注释.它包含一个
MapPresentable类型的对象. @H_419_8@

@H_419_8@

protocol MapPresentable {    associatedtype AnnotationElement: MKAnnotation    var annotations: [AnnotationElement] { get }}class MapVIEwController<M: MapPresentable>: UIVIEwController {    var mapPresentable: M!}
@H_419_8@如果mapPresentable符合RoutePresentable协议,MapVIEwController还可以在地图上显示路线.

@H_419_8@

protocol RoutePresentable: MapPresentable {    var getRouteLocations: [CLLocation] { get }}
@H_419_8@但是在MapVIEwController中进行检查时

@H_419_8@

if let routePresentable = mapPresentable as? RoutePresentable {    showRoute(routePresentable.getRouteLocations)}
@H_419_8@我有这个错误:

@H_419_8@

Protocol 'RoutePresentable' can only be used as a generic constraint because it has Self or associated type requirements
解决方法 更新 @H_419_8@

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

@H_419_8@希望这会有所帮助.

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

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

@H_419_8@

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)}
@H_419_8@原版的

@H_419_8@因为routePresentable.annotations的类型未提供,

@H_419_8@您可以删除关联类型AnnotationElement:MKAnnotation.

@H_419_8@或者用户通用结构代替:

@H_419_8@

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 – 协议只能用作通用约束所遇到的程序开发问题。

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

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/web/1005646.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-22
下一篇 2022-05-22

发表评论

登录后才能评论

评论列表(0条)

保存