Skip to content

Instantly share code, notes, and snippets.

Last active January 15, 2023 13:03
What would you like to do?
// 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
Copy link

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.

Copy link

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

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