0

I am currently trying to complete an online tutorial on reading JSON files the tutorial file has us input the following code

override func viewDidLoad() {
    super.viewDidLoad()

    if let url = NSURL(string: "https://api.forecast.io/forecast/d3250bf407f0579c8355cd39cdd4f9e1/37.7833,122.4167") {
        if let data = NSData(contentsOfURL: url){
            do {
                let parsed = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments)

                let newDict = parsed as? NSDictionary
                print(newDict!["currently"]!["summary"])
            }
            catch let error as NSError {
                print("A JSON parsithng error occurred, here are the details:\n \(error)")
            }
        }
    }
}

}

When I put that into swift it auto corrects most of the code to:

override func viewDidLoad() {
    super.viewDidLoad()

    if let url = URL(string: "https://api.forecast.io/forecast/d3250bf407f0579c8355cd39cdd4f9e1/42.2111,-88.3162") {
        if let data = NSData(contentsOf: url){
            do {
                let parsed = try JSONSerialization.jsonObject(with: data as Data, options: JSONSerialization.ReadingOptions.allowFragments)

                let newDict = parsed as? NSDictionary
                print(newDict!["currently"]!["summary"])
            }
            catch let error as NSError {
                print("A JSON parsithng error occurred, here are the details:\n \(error)")
            }
        }
    }
}

I am now getting an error on the line print(newDict!["currently"]!["summary"]) because Type 'Any' has no subscript members, and Im not sure how to fix it. Removing the ! produces an error that says that there must be a ! or an ? but putting either brings me back to this 'Any' Error. Any help you could lend would be very much appreciated

  • Don't use `NSDictionary` in Swift. Use a Swift dictionary. Also avoid `NSData` and `NSError`. This is Swift code, not Objective-C. – rmaddy Oct 14 '18 at 23:26
  • Please [search on the error](https://stackoverflow.com/search?q=%5Bswift%5D+Type+%27Any%27+has+no+subscript+members) before posting. This error has been covered many times before. – rmaddy Oct 14 '18 at 23:27

1 Answers1

1

You can try

if let newDict = parsed as? [String:Any] {
   if let curr = newDict["currently"] as? [String:Any] {
      print(curr["summary"])
   }
}

As this newDict!["currently"]! will return Any that you can't subscript with ["summary"] until you cast it to [String:Any]

Shehata Gamal
  • 98,760
  • 8
  • 65
  • 87