Created
March 23, 2020 06:39
-
-
Save madcato/09d1d0cae392508507cbd7410273d845 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
// To decode a json where the type to decode is in the json itself like: | |
// [{ "type": "foo", "payload": { "word": "hello" "push_id": 3711282988, "size": 1, } }, { "type": "bar", "payload": { "size": 1, "radious": 0.5 } }] | |
struct FooPayload: Codable { | |
var word: String | |
var push_id: Int | |
var size: Int | |
} | |
struct BarPayload: Codable { | |
var size: Int | |
var radious: Double | |
} | |
struct Foo { | |
var type: String | |
var payload: Payload? | |
enum CodingKeys : CodingKey { | |
case type, payload | |
} | |
init(from decoder: Decoder) throws { | |
let values = try decoder.container(keyedBy: CodingKeys.self) | |
type = try values.decode(String.self, forKey: .type) | |
swith type { | |
case "foo": | |
payload = values.decode(FooPayload.self, forKey: .payload) | |
case "bar": | |
payload = values.decode(BarPayload.self, forKey: .payload) | |
default: | |
payload = nil | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment