gpt4 book ai didi

swift - 协议(protocol)只能用作通用约束

转载 作者:搜寻专家 更新时间:2023-10-31 08:25:18 25 4
gpt4 key购买 nike

我有一个 MapViewController 用于在 map 上显示注释。它包含一个MapPresentable 类型的对象。

protocol MapPresentable {
associatedtype AnnotationElement: MKAnnotation
var annotations: [AnnotationElement] { get }
}

class MapViewController<M: MapPresentable>: UIViewController {
var mapPresentable: M!
}

如果 mapPresentable 符合 RoutePresentable 协议(protocol),MapViewController 也可以在 map 上呈现路线。

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

最佳答案

已更新

对不起,我错了。但是无法使用关联类型 转换协议(protocol)。

希望这会有所帮助。

据我所知,routePresentable.getRouteLocations 与协议(protocol) MapPresentable 无关。

所以你可以将RoutePresentable分成两个协议(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的Type没有提供,

您可以只删除 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)
}

关于swift - 协议(protocol)只能用作通用约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40334856/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com