Swift 3.0: Data to JSON

Evening, I’m trying to creating an APIClient, but I’m having a problem with a warning:
APIClient.swift:53:81: Cast from 'Data' to unrelated type '[String : Any]' always fails

In this code I’m trying to convert Data into JSON as a dictionary [String : Any].

  • Swift addObject
  • Parsing JSON data from alamofire into Array with Dictionary
  • Unwrapping Json Swift (found nil)
  • Turn swift object into a JSON string
  • Sort NSDictionary in ascending order
  • Parse JSON Swift 3
  • I guess the compiler can’t know if this cast could or could not be possible so it throws the error, but I’m pretty sure it will work. So how can I avoid this warning or how can I write safer code?

    case 200:
             do {
                let json = try JSONSerialization.data(withJSONObject: data!, options: []) as? [String : Any]
                completion(json, HTTPResponse, nil)
             } catch let error {
                 completion(nil, HTTPResponse, error)
             }
    

    Solutions Collect From Internet About “Swift 3.0: Data to JSON”

    The right method is:

    let json = try JSONSerialization.jsonObject(with: data!, options: []) as? [String : Any]
    

    Thanks to Eric Aya