Marco Koivisto
Marco Koivisto

Reputation: 52

Cast NSArray to NSDictionary

I want to cast jsonResult to NSDicitonary to be able to do a callback of jsonResult. Is this possible?

func request(url:String,callback:(NSDictionary)->()) {
        let nsURL = NSURL(string: url)
        let session = NSURLSession.sharedSession()
        let task = session.dataTaskWithURL(nsURL!, completionHandler: { (data, response, error) -> Void in

            if error != nil {

                print(error)

            } else {

                do {
                    let jsonResult = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as! NSArray

                    print(jsonResult[0])



                } catch {
                    print("my error")
                }

            }

        })

Upvotes: 1

Views: 3128

Answers (1)

Eric Aya
Eric Aya

Reputation: 70098

If I understand your question, you can use optional binding to cast your object:

if let jsonResult = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? NSArray {
    if let dict = jsonResult[0] as? NSDictionary {
        callback(dict)
    }
}

Upvotes: 2

Related Questions