2015-09-29 52 views
18

我工作的代碼刪除所有地圖標註有一個按鈕,但我更新的Xcode 7後,我遇到了錯誤:如何刪除所有地圖標註在SWIFT 2

類型「MKAnnotation」不符合協議「序列類型」

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

回答

40

在夫特2 annotations被聲明爲非可選的陣列[MKAnnotation]所以可以很容易地寫出

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

而不任何類型的鑄造。

+0

工作很好!謝謝! – user4812000

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

如果您不想刪除用戶位置。

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

注意:Objective-C現在有泛型,不再需要轉換'annotations'數組的元素。

+0

我想使用你的代碼,但它說:意外地發現無,而...我知道這意味着什麼,但我不知道哪個值是零。 – Lenny1357

0

問題是有兩種方法。一個是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)將刪除所有註釋。 如果你得到一個零,這意味着你有一個空的數組。你可以通過在if後添加一個else語句來驗證,就像這樣;

else{print("empty array")} 
相關問題