Created
July 6, 2018 00:06
-
-
Save aciidgh/1f0e129d73aa1a57b8a885fc207a3b6a 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
import Foundation | |
struct StringCodingKey: CodingKey { | |
var stringValue: String | |
init(stringValue: String) { | |
self.stringValue = stringValue | |
} | |
var intValue: Int? { return nil } | |
init?(intValue: Int) { fatalError() } | |
} | |
@dynamicMemberLookup | |
struct Key { | |
subscript(dynamicMember member: String) -> StringCodingKey { | |
return StringCodingKey(stringValue: member) | |
} | |
} | |
struct Model { | |
let name: String | |
let age: Int | |
init(name: String, age: Int) { | |
self.name = name | |
self.age = age | |
} | |
} | |
extension Model: Decodable { | |
init(from decoder: Decoder) throws { | |
let key = Key() | |
let container = try decoder.container(keyedBy: StringCodingKey.self) | |
name = try container.decode(String.self, forKey: key.name) | |
age = try container.decode(Int.self, forKey: key.age) | |
} | |
} | |
let j1 = """ | |
{ | |
"name": "Ankit", | |
"age": 25 | |
} | |
""".data(using: .utf8)! | |
print(try JSONDecoder().decode(Model.self, from: j1)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment