Reputation: 7668
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?
do {
let json = try JSONSerialization.data(
withJSONObject: data!,
options: []
) as? [String : Any]
completion(json, HTTPResponse, nil)
} catch let error {
completion(nil, HTTPResponse, error)
}
Upvotes: 41
Views: 79592
Reputation: 5943
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 data {
do{
return try JSONDecoder().decode(T.self, from: data)
} 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)
Upvotes: 1