Skip to content

Instantly share code, notes, and snippets.

@erikbasargin
Last active October 21, 2020 21:44
Show Gist options
  • Select an option

  • Save erikbasargin/a46fabe931359b6d8563a9109a5ef811 to your computer and use it in GitHub Desktop.

Select an option

Save erikbasargin/a46fabe931359b6d8563a9109a5ef811 to your computer and use it in GitHub Desktop.
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