2016-12-18 28 views
0

以下函數我遍歷plist中的項目,這在Swift 1中工作得很好,也許Swift 2,但絕對不是Swift 3.在試圖重新定義NSDictionary作爲Dictionary之後,它要求將要存儲在字典中的類型,但是當嘗試不同的變體例如字符串甚至任何變體時,它不會編譯。因此,我轉回保持它作爲一個NSDictionary但這種錯誤我難住了:點,標題,typeRawValue和字幕:設置常量時類型'NSDictionary.Iterator.Element'(aka'(key:Any,value:Any)')沒有下標成員

Type 'NSDictionary.Iterator.Element' (aka '(key: Any, value: Any)') has no subscript members 

這個錯誤出現。

func addAttractionPins() { 

      var myDict: NSDictionary? 
      if let filePath = Bundle.main.path(forResource: "GeorgiaHumanAnnotations", ofType: "plist"){ 
       myDict = NSDictionary(contentsOfFile: filePath) 
      } 
      if let dict = myDict { 
       for attraction in dict { 
        let point = CGPointFromString(attraction["location"] as! String) 
        let coordinate = CLLocationCoordinate2DMake(CLLocationDegrees(point.x), CLLocationDegrees(point.y)) 
        let title = attraction["name"] as! String 
        let typeRawValue = Int((attraction["type"] as! String))! 
        let type = HumanAnnotationType(rawValue: typeRawValue)! 
        let subtitle = attraction["subtitle"] as! String 
        let annotation = HumanAnnotation(coordinate: coordinate, title: title, subtitle: subtitle, type: type) 
        mapView.addAnnotation(annotation) 
       } 
      } 
} 

這裏是plist中的截圖: enter image description here 如果您還需要進一步的代碼來了解發生了什麼事情,請不要猶豫,問及感謝您對任何人的提前幫助。

+1

NSDictionary'?使用Swift字典。 – rmaddy

+0

@rmaddy我確實考慮過它,因爲你知道它會要求聲明字典的類型,但是當我嘗試字符串類型或甚至任何類型時,它給了我更多的錯誤。 –

+2

你確定plist的根目標是字典嗎?你正在使用一個數組枚舉器。 – vadian

回答

1

我不知道,你最後的評論表示您已經成功轉換你的代碼,但看到你的plist中的形象,你的代碼可以重新寫成這樣:你爲什麼要使用`

if 
     let filePath = Bundle.main.path(forResource: "GeorgiaHumanAnnotations", ofType: "plist"), 
     let dictArray = NSArray(contentsOfFile: filePath) as? [[String: Any]] 
    { 
     for attraction in dictArray { 
      let point = CGPointFromString(attraction["location"] as! String) 
      let coordinate = CLLocationCoordinate2DMake(CLLocationDegrees(point.x), CLLocationDegrees(point.y)) 
      let title = attraction["name"] as! String 
      let typeRawValue = Int((attraction["type"] as! String))! 
      let type = HumanAnnotationType(rawValue: typeRawValue)! 
      let subtitle = attraction["subtitle"] as! String 
      let annotation = HumanAnnotation(coordinate: coordinate, title: title, subtitle: subtitle, type: type) 
      mapView.addAnnotation(annotation) 
     } 
    } 
相關問題