Created
April 24, 2020 01:13
-
-
Save priore/f6143a023a6c46e0536aa5de5631af47 to your computer and use it in GitHub Desktop.
Passing Decodable object as generic parameter
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
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