Skip to content

Instantly share code, notes, and snippets.

@twostraws
Last active January 15, 2023 13:03
Show Gist options
  • Star 61 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save twostraws/01464739fed1d202dd0adc663e19d547 to your computer and use it in GitHub Desktop.
Save twostraws/01464739fed1d202dd0adc663e19d547 to your computer and use it in GitHub Desktop.
// A URLSession extension that fetches data from a URL and decodes to some Decodable type.
// Usage: let user = try await URLSession.shared.decode(UserData.self, from: someURL)
// Note: this requires Swift 5.5.
extension URLSession {
func decode<T: Decodable>(
_ type: T.Type = T.self,
from url: URL,
keyDecodingStrategy: JSONDecoder.KeyDecodingStrategy = .useDefaultKeys,
dataDecodingStrategy: JSONDecoder.DataDecodingStrategy = .deferredToData,
dateDecodingStrategy: JSONDecoder.DateDecodingStrategy = .deferredToDate
) async throws -> T {
let (data, _) = try await data(from: url)
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = keyDecodingStrategy
decoder.dataDecodingStrategy = dataDecodingStrategy
decoder.dateDecodingStrategy = dateDecodingStrategy
let decoded = try decoder.decode(T.self, from: data)
return decoded
}
}
@twostraws
Copy link
Author

Note: in an earlier revision I made the return value T? rather than T, which was a mistake. This is corrected in the latest revision.

@twostraws
Copy link
Author

Updated with a default value for T for folks who prefer to use type annotation – thanks @prtmshk!

@dqhieu
Copy link

dqhieu commented Jun 15, 2021

Thanks for sharing 🥳 By the way, the indentation seems off

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment