Zygote Zygote - 1 year ago 86
Swift Question

Swift 3 error: Type 'Any' has no subscript members

So I know this question has been asked and answered numerous times before, but I just migrated my project to Swift 3 and Im getting a ton of these errors in my code that parses JSON and I couldn't quite find answers that made me understand how to resolve my specific issue.

guard let result = try JSONSerialization.jsonObject(with: data!, options: []) as? [String:AnyObject] else {
guard let responseData = result["Data"] else { return }
guard let userData = responseData["UserProfile"] else { return }

var userProfileFieldsDict = [String: String]()

if let sessionToken = userData!["CurrentSessionToken"] as? NSString {
userProfileFieldsDict["sessionToken"] = String(sessionToken)


if let sessionToken
line throws the aforementioned error, but not quite sure how you're supposed to deal with this in Swift 3? Could someone explain and suggest a best practice fix?

Thanks a bunch!

Answer Source

If responseData["UserProfile"] is also a dictionary you'll probably want to cast it as such in you guard by saying guard let userData = responseData["UserProfile"] as? [String : AnyObject] else { return }. I suspect this will solve your problem.

As a small aside, you don't need to force unwrap userData in your if let, because you've already unwrapped it in the guard.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download