Swift 2 MKMapViewDelegate rendererForOverlay compiler warning

余生颓废 提交于 2019-12-23 09:32:48

问题


I am trying to draw a polyline on a map in Swift 2. It all works well, but I get a compiler warning for this code:

func mapView(mapView: MKMapView!, rendererForOverlay overlay: MKOverlay!) -> MKOverlayRenderer! {

    if overlay is MKPolyline {

        let polylineRenderer = MKPolylineRenderer(overlay: overlay)

        polylineRenderer.strokeColor = UIColor.redColor()

        polylineRenderer.lineWidth = 5

        return polylineRenderer
    }

    return nil

}

This will give me a warning says that 'Result and parameters in mapView (rendererForOverlay) have different optionality than expected by protocol MKMapViewDelegate'

Now, this will compile fine, but it bugs me that the compiler warning is showing.

If I change the first line to

func mapView(mapView: MKMapView, rendererForOverlay overlay: MKOverlay) -> MKOverlayRenderer {

by removing the !, the warning will go away but I get an error that the return cannot be nil and the code will not compile anymore.

This is also a follow up to this thread where the same problem was stated but no satisfying answer is available: Swift 2 MKMapViewDelegate rendererForOverlay optionality

Can anyone shed any light on the correct way to use this function now in Swift 2?

Thanks.


回答1:


Going by what autocomplete suggests the prototype looks like this:

func mapView(mapView: MKMapView, rendererForOverlay overlay: MKOverlay) -> MKOverlayRenderer

And apparently there's nothing you can do about it, except for returning return MKPolylineRenderer() where normally you would return nil.

To me it looks like an implementation bug, because here's what the documentation says about the returned object:

The renderer to use when presenting the specified overlay on the map. If you return nil, no content is drawn for the specified overlay object.

I suggest you create a case for it in Apple's bug report




回答2:


Don't return nil. This is only called for overlays you create, so instead of checking if overlay is MKPolyline, check which of your overlays it is. If you have only one, return the specified polyline renderer without checking which one it is.



来源:https://stackoverflow.com/questions/32452067/swift-2-mkmapviewdelegate-rendererforoverlay-compiler-warning

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!