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

use*_*000 27 xcode mapkit swift swift2

我有工作代码用一个按钮删除所有地图注释,但在我更新到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)
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

vad*_*ian 64

在Swift 2 annotations中声明为非可选数组,[MKAnnotation]因此您可以轻松编写

let allAnnotations = self.mapView.annotations
self.mapView.removeAnnotations(allAnnotations)
Run Code Online (Sandbox Code Playgroud)

没有任何类型的铸造.


Dan*_*iel 19

self.mapView.removeAnnotations(self.mapView.annotations)
Run Code Online (Sandbox Code Playgroud)

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

self.mapView.annotations.forEach {
  if !($0 is MKUserLocation) {
    self.mapView.removeAnnotation($0)
  }
}
Run Code Online (Sandbox Code Playgroud)

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


小智 5

环球银行金融电信协会5

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

let annotations = mapView.annotations.filter({ !($0 is MKUserLocation) })
mapView.removeAnnotations(annotations)
Run Code Online (Sandbox Code Playgroud)