如何删除 swift 2 中的所有地图注释

How do I remove all map annotations in swift 2

我有使用按钮删除所有地图注释的工作代码,但在我更新到 xcode 7 之后,我 运行 陷入错误:

类型'MKAnnotation'不符合协议'SequenceType'

if let annotations = (self.mapView.annotations as? MKAnnotation){
    for _annotation in annotations {
        if let annotation = _annotation as? MKAnnotation {
            self.mapView.removeAnnotation(annotation)
        }
    }
}

在Swift 2中annotations被声明为非可选数组[MKAnnotation]所以你可以很容易地写

let allAnnotations = self.mapView.annotations
self.mapView.removeAnnotations(allAnnotations)

没有任何类型转换。

self.mapView.removeAnnotations(self.mapView.annotations)

如果您不想删除用户位置。

self.mapView.annotations.forEach {
  if !([=11=] is MKUserLocation) {
    self.mapView.removeAnnotation([=11=])
  }
}

注意:Objective-C 现在有了泛型,不再需要转换 'annotations' 数组的元素。

问题是有两种方法。一个是带有 MKAnnotation 对象的 removeAnnotation,另一个是带有 MKAnnotations 数组的 removeAnnotations,请注意一个末尾的 "s" 而不是另一个。尝试将数组 [MKAnnotation] 转换为 MKAnnotation 单个对象,反之亦然会使程序崩溃。代码行 self.mapView.annotations 创建一个数组。因此,如果您使用 removeAnnotation 方法,则需要为数组中的单个对象索引数组,如下所示:

let previousAnnotations = self.mapView.annotations
if !previousAnnotations.isEmpty{
  self.mapView.removeAnnotation(previousAnnotations[0])
}

因此,您可以在保留用户位置的同时删除各种注释。在尝试从数组中删除对象之前,您应该始终测试数组,否则可能会出现越界或 nil 错误。

注意:使用方法 removeAnnotations(带有 s)删除所有注释。 如果你得到一个 nil,那意味着你有一个空数组。您可以通过在 if 之后添加 else 语句来验证这一点,例如;

    else{print("empty array")}

SWIFT 5

如果您不想删除用户位置标记:

let annotations = mapView.annotations.filter({ !([=10=] is MKUserLocation) })
mapView.removeAnnotations(annotations)