以下是CCHMapClusterController的代码。我试图将此函数重写为Swift,但我不断收到此错误:
“初始化之前使用的变量注释”
就行了: clusterAnnotation = annotation
我对目标C没有任何线索,有人可以检查我是否正确地完成了最后几行吗?
目标C:
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation: (id<MKAnnotation>)annotation
{
MKAnnotationView *annotationView;
if ([annotation isKindOfClass:CCHMapClusterAnnotation.class]) {
static NSString *identifier = @"clusterAnnotation";
ClusterAnnotationView *clusterAnnotationView = (ClusterAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:identifier];
if (clusterAnnotationView) {
clusterAnnotationView.annotation = annotation;
} else {
clusterAnnotationView = [[ClusterAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:identifier];
clusterAnnotationView.canShowCallout = YES;
}
CCHMapClusterAnnotation *clusterAnnotation = (CCHMapClusterAnnotation *)annotation;
clusterAnnotationView.count = clusterAnnotation.annotations.count;
clusterAnnotationView.blue = (clusterAnnotation.mapClusterController == self.mapClusterControllerBlue);
clusterAnnotationView.uniqueLocation = clusterAnnotation.isUniqueLocation;
annotationView = clusterAnnotationView;
}
return annotationView;
}
Swift Code:
func mapView(mapView: MKMapView!, viewForAnnotation annotation: MKAnnotation!) -> MKAnnotationView! {
if annotation is MKUserLocation {
// return nil so map view draws "blue dot" for standard user location
return nil
}
var annotationView : MKAnnotationView?
if annotation is CCHMapClusterAnnotation {
// let a : clusterAnnotationView = annotation as clusterAnnotationView
let identifier: NSString = "clusterAnnotation"
var clusterAnnotationView = (mapView.dequeueReusableAnnotationViewWithIdentifier(identifier as String)) as? ClusterAnnotationView!
if (clusterAnnotationView != nil) {
clusterAnnotationView!.annotation = annotation
} else {
clusterAnnotationView = ClusterAnnotationView(annotation: annotation, reuseIdentifier: "clusterAnnotation")
clusterAnnotationView!.canShowCallout = true
}
var clusterAnnotation : CCHMapClusterAnnotation;
var annotation : CCHMapClusterAnnotation
clusterAnnotation = annotation
clusterAnnotationView.count = clusterAnnotation.annotations.count
clusterAnnotationView!.blue = (clusterAnnotation.mapClusterController == self.mapClusterControllerBlue);
clusterAnnotationView!.uniqueLocation = clusterAnnotation.isUniqueLocation();
annotationView = clusterAnnotationView
}
答案 0 :(得分:1)
使用这些行:
var clusterAnnotation : CCHMapClusterAnnotation;
var annotation : CCHMapClusterAnnotation
clusterAnnotation = annotation
声明了两个变量但未初始化,因此您会收到该警告。
此外,它还声明了一个与现有annotation
参数同名的新本地变量annotation
。您可能也会收到警告或错误。
如果您正在尝试转换此Objective-C行:
CCHMapClusterAnnotation *clusterAnnotation =
(CCHMapClusterAnnotation *)annotation;
投射 annotation
参数为CCHMapClusterAnnotation
,然后可能的Swift版本为:
let clusterAnnotation = annotation as? CCHMapClusterAnnotation
但是,您也可以将上面的注释类检查(if annotation is ...
)与此类转换组合结合使用:
if let clusterAnnotation = annotation as? CCHMapClusterAnnotation {
...
}