You get no error because of this:
if let decodedResponce = try? JSONDecoder().decode(Responce.self, from: data) {
results = decodedResponce.results
}
try?
returns an Optional
and converts any error into nil
, which means you won't know what that error is.
Do this instead:
let decodedResponce = try JSONDecoder().decode(Responce.self, from: data) {
results = decodedResponce.results
And then in the catch
clause, print(error)
instead of the unhelpful print("Invalid data")
BTW, this:
guard let url = URL(string:
"https://itunes.apple.com/search?term=keith+urban&entity=song") else {
print("Invalid URL")
return
}
is pretty pointless. It will never be nil
. You can just do:
let url = URL(string:
"https://itunes.apple.com/search?term=keith+urban&entity=song")!
The unwrap is safe because the only reason URL.init(string:)
would return nil
is if you pass it invalid characters. URL
doesn't validate anything except that the string is not empty and the characters are valid. Since you are giving it a static string with valid characters, you know with 100% certainty that is not the case.
You only need to use the guard
form if you are constructing the URL from user-supplied data that you can't guarantee will be valid.