【问题标题】:'MKPinAnnotationView' is not convertible to '()''MKPinAnnotationView' 不能转换为 '()'
【发布时间】:2014-10-22 21:20:01
【问题描述】:

我正在尝试将一段 Objective-C 代码翻译/转换为 Swift。
这是 Objective-C 的原文:

#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;
}

这是 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
}

这是错误:

我不完全理解编译器试图对我说什么。
“annotationView”类是函数返回类型的子类:MKAnnotationView。

【问题讨论】:

    标签: swift compiler-errors return-value


    【解决方案1】:

    您的 func 签名缺少返回类型:

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

    没有明确的返回类型,swift 默认为一个空元组,这意味着没有返回类型 - 这就是错误消息所说的,可能不是以明确的方式:)

    【讨论】:

    • 简单的监督。谢谢。
    【解决方案2】:

    这是编译好的完整函数:

    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!
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-02-10
      • 2023-03-22
      • 2013-12-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多