Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift 3.0: Data to JSON [String : Any]

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].

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)          } 
like image 215
Andrea Miotto Avatar asked Sep 10 '16 15:09

Andrea Miotto


People also ask

What is JSONSerialization in Swift?

An object that converts between JSON and the equivalent Foundation objects.

What is JSON serialization?

Json namespace provides functionality for serializing to and deserializing from JavaScript Object Notation (JSON). Serialization is the process of converting the state of an object, that is, the values of its properties, into a form that can be stored or transmitted.


1 Answers

The right method is:

do{   let json = try JSONSerialization.jsonObject(with: data!, options: []) as? [String : Any] }catch{ print("erroMsg") } 

Thanks to Eric Aya

like image 174
Andrea Miotto Avatar answered Oct 17 '22 08:10

Andrea Miotto