This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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 | |
} | |
} |
Updated with a default value for T for folks who prefer to use type annotation – thanks @prtmshk!
Thanks for sharing
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Note: in an earlier revision I made the return value
T?
rather thanT
, which was a mistake. This is corrected in the latest revision.