2017-03-02 102 views
0

我想獲取已被編碼爲json在php腳本中的數據。模糊使用去'下標'

我的代碼:

func getJson(completion: @escaping (Array<CarPark>) -> Void) { 

     activityIndicatior.center = self.view.center 
     activityIndicatior.hidesWhenStopped = true 
     activityIndicatior.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.gray 
     view.addSubview(activityIndicatior) 
     self.activityIndicatior.startAnimating() 

     let task = URLSession.shared.dataTask(with: url!) { (data, response, error) in 
      if error != nil 
      { 
       print("ERROR") 
      } 
      else 
      { 
       if let content = data 
       { 

        do{ 

         let myJson = try JSONSerialization.jsonObject(with: content, options: JSONSerialization.ReadingOptions.mutableContainers) as AnyObject 

         for index in 0..<myJson.count { 

          if let entry = myJson[index] as? NSDictionary{ 
          let name = entry["Name"] as! String 
          let longitude = Double(entry["Longitude"] as! String) 
          let latitude = Double(entry["Latitude"] as! String) 

          let quiet = Int(entry["Quiet"] as! String) 
         let moderate = Int(entry["Moderate"] as! String) 

          let busy = Int(entry["Busy"] as! String) 
          let coordinate = CLLocationCoordinate2D(latitude: latitude!, longitude: longitude!) 

          print("coordinate lat is : \(coordinate.latitude)") 
          print("coordinate long is : \(coordinate.longitude)") 
          print("coordinate full is: \(coordinate)") 
          let tempPark = CarPark(name: name, latitude: latitude!, longitude: longitude!, quiet: quiet!, moderate: moderate!, busy: busy!, coordinate: coordinate, level: "Nil") 
          let level = tempPark.calcAvailability() 
          tempPark.level = level 
          print("Availability is \(tempPark.level)") 
          self.tempCarParks.append(tempPark) 
          // print("amount of parks: \(self.carParks.count)") 
          print("name of parks in array: \(self.tempCarParks[index].name)") 
          print("Availability is \(tempPark.level)") 
          } 

         } 
         completion(self.tempCarParks) 

        } 
        catch 
        { 
         print("Error") 
        } 
       } 
      } 
    } 

     task.resume() 

    } 

我收到寫着 '曖昧使用的下標' 的錯誤在該行:

如果讓入門= myJson [指數]作爲? NSDictionary {

我該如何解決這個問題?

回答

0

既然你知道myJson是一個數組,你爲什麼要將對象投射到未指定AnyObject

這會導致錯誤,編譯器需要知道所有下標對象的具體類型。幫助編譯器則編譯器可以幫助你:

let myJson = try JSONSerialization.jsonObject(with: content) as! [[String:Any]] 

    for entry in myJson { // don't use old-fashioned index based loops 

    let name = entry["Name"] as! String 
... 

.mutableContainers是斯威夫特完全無用。