gpt4 book ai didi

swift - 非 -'@objc' 方法不满足带有条件扩展的 '@objc' 协议(protocol)的可选要求

转载 作者:IT王子 更新时间:2023-10-29 05:38:22 38 4
gpt4 key购买 nike

我正在尝试使用条件扩展创建 MKMapViewDelegate 的默认实现,如下所示:

extension MKMapViewDelegate where Self: NSObject {
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
...
}

func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
...
}
}

但是当我编译代码时,我收到了警告

Non-'@objc' method 'mapView(_:viewFor:)' does not satisfy optional requirement of '@objc' protocol 'MKMapViewDelegate'

我预计“Self”与 NSObject 的一致性意味着警告不会发生。除了警告之外,即使委托(delegate)实例是 UIViewController 并因此符合 NSObject,也不会调用委托(delegate)方法。

我是否误解了“where”在扩展程序中的工作方式?

最佳答案

NSObject 由于接受了 Doug Gregor's proposal: SE-0160.,自 Swift 4 起将不再推断 @objc

我承认我没有花时间去了解你的错误背后的原因。我只是发布了这个答案,希望阅读您的问题的任何其他人都能看到以下建议。

为整个模块的协议(protocol)提供默认实现是不好的做法或“代码味道”。我会推荐一种替代方法,其中您创建一个自定义类型,例如 MapViewDelegate,它具有一些默认行为,可以在明确符合该 protocol 的类型之间共享。

例如:

import MapKit
protocol MapViewDelegate: MKMapViewDelegate {}
extension MapViewDelegate where Self: NSObject {
func annotationView(for annotation: MKAnnotation, in mapView: MKMapView) -> MKAnnotationView? {

}

func renderer(for overlay: MKOverlay, in mapView: MKMapView) -> MKOverlayRenderer {

}
}
final class MyMapDelegate: NSObject, MapViewDelegate {
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
return annotationView(for: annotation, in: mapView)
}
func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
return renderer(for: overlay, in: mapView)
}
}

关于swift - 非 -'@objc' 方法不满足带有条件扩展的 '@objc' 协议(protocol)的可选要求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39118030/

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