简体   繁体   中英

'MKPinAnnotationView' is not convertible to '()'

I'm trying to translate/convert piece of Objective-C code to Swift.
Here's the Objective-C original:

#pragma mark - MKMapViewDelegate

- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation
{
    MKPinAnnotationView *annotationView = nil;
    if ([annotation isKindOfClass:[PlaceAnnotation class]])
    {
        annotationView = (MKPinAnnotationView *)[self.mapView dequeueReusableAnnotationViewWithIdentifier:@"Pin"];
        if (annotationView == nil)
        {
            annotationView = [[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"Pin"];
            annotationView.canShowCallout = YES;
            annotationView.animatesDrop = YES;
        }
    }
    return annotationView;
}

Here's the Swift:

func mapView(mapView:MKMapView, annotation:MKAnnotation) {

    var annotationView = mapView.dequeueReusableAnnotationViewWithIdentifier("Pin") as? MKPinAnnotationView

    if annotationView == nil {
        annotationView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: "Pin")
        annotationView!.canShowCallout = true
        annotationView!.animatesDrop = true
    }

    return annotationView
}

Here's the error: 在此处输入图片说明

I don't fully understand what the compiler is trying to say to me.
'annotationView'class is a subclass to the function's return type: MKAnnotationView.

Your func signature is missing the return type:

func mapView(mapView:MKMapView, annotation:MKAnnotation) -> MKPinAnnotationView {

without an explicit return type, swift defaults to an empty tuple, which means no return type - that is what the error message says, maybe not in an explicit way :)

Here's the completed function which compiles okay:

func mapView(mapView:MKMapView, annotation:MKAnnotation) -> MKPinAnnotationView {

    var annotationView = mapView.dequeueReusableAnnotationViewWithIdentifier("Pin") as? MKPinAnnotationView

    if annotationView == nil {
        annotationView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: "Pin")
        annotationView!.canShowCallout = true
        annotationView!.animatesDrop = true
    }

    return annotationView!
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM