-2

I'm currently trying to learn Swift. I'm using APIs and JSON for this practice problem. At the print statement that tries to display the name it gives me the error:

"Type 'Any' has no subscript members".

Can someone explain to me what it means by no subscript member and what I can do to fix this problem? I've tried looking at other problems on Stack Overflow but can't come up with anyway to solve this.

override func viewDidLoad() {
    super.viewDidLoad()

    let url = URL(string: "https://www.googleapis.com/blogger/v3/blogs/2399953/posts?key=AIzaSyDRiJilhWCEkMeEi40ONIPI3eDWukA0mQo")

    let task = URLSession.shared.dataTask(with: url!) { (data, response, error) in
        if error != nil {
            print("Error in URL")
        } else {
            do {
                let jsonResults = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers) as AnyObject

                let items = (jsonResults["items"]!)!

                for item in items as! [AnyObject] {
                    print(item["author"]?["displayName"]!)
                }
            } catch {
                print("Error in JSON")
            }
        }
    }
    task.resume()
}
rmaddy
  • 314,917
  • 42
  • 532
  • 579

1 Answers1

1

It's a bad thing to case anything to AnyObject. BE specific about what you will get and if you are not then you can use guard statement to avoid crashing.

if let jsonResults = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers) as? Dictionary<String, AnyObject>{
    if let items = jsonResults["items"] as? Array<Dictionary<String, AnyObject>>{
        for item in items {
            guard let dictAuthorDetails = item["author"] else {
                continue
            }
            print(dictAuthorDetails["displayName"])
        }
    }
}
Sohil R. Memon
  • 9,404
  • 1
  • 31
  • 57