Last active
October 21, 2020 21:44
-
-
Save erikbasargin/a46fabe931359b6d8563a9109a5ef811 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| struct Test<T>: Codable where T: Codable { | |
| enum CodingKeys: String, CodingKey { | |
| case value | |
| } | |
| let value: T | |
| let info: String | |
| } | |
| extension Test { | |
| init(from decoder: Decoder) throws { | |
| let container = try decoder.container(keyedBy: CodingKeys.self) | |
| self.value = try container.decode(T.self, forKey: .value) | |
| self.info = "Default init(from decoder:)" | |
| } | |
| } | |
| extension Test where T == String { | |
| init(from decoder: Decoder) throws { | |
| let container = try decoder.container(keyedBy: CodingKeys.self) | |
| self.value = try container.decode(T.self, forKey: .value) | |
| self.info = "Custom init(from decoder:)" | |
| } | |
| } | |
| let data = #"{"value":"Hello, World!"}"#.data(using: .utf8)! | |
| let object = try? JSONDecoder().decode(Test<String>.self, from: data) | |
| print(object.debugDescription) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment