40

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)
         }
duncan
  • 31,401
  • 13
  • 78
  • 99
Andrea Miotto
  • 7,084
  • 8
  • 45
  • 70

2 Answers2

93

The right method is:

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

Thanks to Eric Aya

Iulian Onofrei
  • 9,188
  • 10
  • 67
  • 113
Andrea Miotto
  • 7,084
  • 8
  • 45
  • 70
1

for Swift 5.*

with this function you can decode your api data to your codable struct, its also nice to catch to decoding errors detailed.

  func decodeDataToObject<T: Codable>(data : Data?)->T?{
        
        if let dt = data{
            do{
              
               return try JSONDecoder().decode(T.self, from: dt)
            
        }  catch let DecodingError.dataCorrupted(context) {
            print(context)
        } catch let DecodingError.keyNotFound(key, context) {
            print("Key '\(key)' not found:", context.debugDescription)
            print("codingPath:", context.codingPath)
        } catch let DecodingError.valueNotFound(value, context) {
            print("Value '\(value)' not found:", context.debugDescription)
            print("codingPath:", context.codingPath)
        } catch let DecodingError.typeMismatch(type, context)  {
            print("Type '\(type)' mismatch:", context.debugDescription)
            print("codingPath:", context.codingPath)
        } catch {
            print("error: ", error)
        }
        }
        
        return nil
    }

usage; let user:User = decodeDataToObject(data: data)

Bilal Şimşek
  • 5,453
  • 2
  • 19
  • 33