Skip to content

Instantly share code, notes, and snippets.

@priore
Created April 24, 2020 01:13
Show Gist options
  • Save priore/f6143a023a6c46e0536aa5de5631af47 to your computer and use it in GitHub Desktop.
Save priore/f6143a023a6c46e0536aa5de5631af47 to your computer and use it in GitHub Desktop.
Passing Decodable object as generic parameter
extension Decodable
{
init(_ data: Data) throws {
self = try JSONDecoder().decode(Self.self, from: data)
}
}
extension Data
{
func toObject<T>() throws -> T?
{
let decode = T.self as? Decodable.Type
assert(decode != nil, "Requires that '\(T.self)' conform to 'Decodable'.")
return try decode?.init(self) as? T
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment