Jared Hughes
Jared Hughes

Reputation: 23

Type '[AnyHashable : Any]?' has no subscript members - Using Moltin API

I'm doing a tutorial from 2015 and very new to swift, I'm getting the Type [AnyHashable : Any]? has no subscript members error from the self.objects line.

Moltin.sharedInstance().product.listing(withParameters: nil, success: { (responseDictionary)-> Void in
      //Assign Products array to object property
      self.objects = responseDictionary["result"] as! [AnyObject]

  }) { (responseDictionary, error) in
      print("Something went wrong!")
  }
}

Upvotes: 1

Views: 2099

Answers (1)

NSAdi
NSAdi

Reputation: 1253

Refactored your code to properly cast the response into a dictionary.

Moltin.sharedInstance().product.listing(withParameters: nil, success: { (response) -> Void in
    //Assign Products array to object property

    guard let responseDictionary = response as? [String: AnyObject] else {
        return
    }

    self.objects = responseDictionary["result"] as! [AnyObject]
    print(self.objects)
    //Tell the table view to reload it's data
    self.tableView.reloadData()
}) { (responseDictionary, error) in
    print("Something went wrong!")
}

I tried running your code after this, it works alright. The API isn't returning what you expect. Let's take a look...

let pagination = responseDictionary["pagination"]!
let results = responseDictionary["result"] as! [AnyObject]

print(pagination.count) // 8
print(results.count) // 0

As you can see there are 8 value under the pagination key but 0 under the results key. Which means that the parsing logic is correct. If there is an error it's on the API end. The API doesn't return any results, that's why the table is empty.

Hard luck, I hope this helps though!

Upvotes: 2

Related Questions