dpbataller
dpbataller

Reputation: 1207

Casting AnyObject to Dictionary in swift

I'm getting data from iTunes API with AFNetworking and I want to create a Dictionary with the response but I can't do it.

Error: Cannot convert the expression's type "Dictionary " to type "Hashable"

This is my code:

func getItunesStore() {

        self.manager.GET( "https://itunes.apple.com/es/rss/topfreeapplications/limit=10/json",
            parameters: nil,
            success: { (operation: AFHTTPRequestOperation!,responseObject: AnyObject!) in
                var jsonResult: Dictionary = responseObject as Dictionary

            },
            failure: { (operation: AFHTTPRequestOperation!,error: NSError!) in
                println("Error:" + error.localizedDescription)
            })

    }

Upvotes: 52

Views: 58392

Answers (1)

Nate Cook
Nate Cook

Reputation: 93296

When you define a Dictionary in Swift you have to give key and value types as well. Something like:

var jsonResult = responseObject as Dictionary<String, AnyObject>

If the cast fails, however, you'll get a runtime error -- you're better off with something like:

if let jsonResult = responseObject as? Dictionary<String, AnyObject> {
    // do whatever with jsonResult
}

Upvotes: 130

Related Questions