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

Xcode 如何删除swift 2中的所有地图注释,xcode,swift,mapkit,swift2,Xcode,Swift,Mapkit,Swift2,我用一个按钮删除了所有地图注释,但在更新到xcode 7后,我遇到了错误: 类型“MKAnnotation”不符合协议“SequenceType” if let annotations = (self.mapView.annotations as? MKAnnotation){ for _annotation in annotations { if let annotation = _annotation as? MKAnnotation { se

我用一个按钮删除了所有地图注释,但在更新到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中,注释被声明为非可选数组
[MKAnnotation]
,因此您可以轻松编写

let allAnnotations = self.mapView.annotations
self.mapView.removeAnnotations(allAnnotations)
没有任何类型的铸造

self.mapView.removeAnnotations(self.mapView.annotations)
如果不想删除用户位置

self.mapView.annotations.forEach {
  if !($0 is MKUserLocation) {
    self.mapView.removeAnnotation($0)
  }
}

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

问题是有两种方法。一个是removeAnnotation,它接受一个MKAnnotation对象,另一个是removeAnnotations,它接受一个MKAnnotations数组,注意其中一个末尾的“s”,而不是另一个。试图从
[MKAnnotation]
强制转换单个对象的数组或从
MKAnnotation
强制转换单个对象的数组将导致程序崩溃。代码行self.mapView.annotations创建一个数组。因此,如果使用removeAnnotation方法,则需要为数组中的单个对象索引数组,如下所示:

let previousAnnotations = self.mapView.annotations
if !previousAnnotations.isEmpty{
  self.mapView.removeAnnotation(previousAnnotations[0])
}
因此,您可以在保留用户位置的同时删除各种注释。在尝试从数组中删除对象之前,应该始终测试数组,否则可能会出现越界或零错误

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

    else{print("empty array")}

SWIFT 5

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

let annotations = mapView.annotations.filter({ !($0 is MKUserLocation) })
mapView.removeAnnotations(annotations)

我想使用你的代码,但它说:意外发现零,而。。。我知道这意味着什么,但我不知道哪个值是零。