Skip to content

Instantly share code, notes, and snippets.

@donnywals
Last active October 29, 2021 12:16
Show Gist options
  • Save donnywals/6ae5ddfae7c1552323325e06dec917b7 to your computer and use it in GitHub Desktop.
Save donnywals/6ae5ddfae7c1552323325e06dec917b7 to your computer and use it in GitHub Desktop.
import Foundation
enum TargetEnum: Codable {
case first(SomeObject)
case second(OtherObject)
enum CodingKeys: CodingKey {
case type
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
let type = try container.decode(String.self, forKey: .type)
switch type {
case "first":
try self = .first(SomeObject(from: decoder))
case "second":
try self = .second(OtherObject(from: decoder))
default:
let context = DecodingError.Context(codingPath: decoder.codingPath,
debugDescription: "Unexpected type: \(type)")
throw DecodingError.dataCorrupted(context)
}
}
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
switch self {
case .first(let object):
try container.encode("first", forKey: .type)
try object.encode(to: encoder)
case .second(let object):
try container.encode("second", forKey: .type)
try object.encode(to: encoder)
}
}
}
struct SomeObject: Codable {
let name: String
}
struct OtherObject: Codable {
let number: Int
}
// Encoding
let anObject = SomeObject(name: "Hello, World!")
let valueToEncode = TargetEnum.first(anObject)
let encoded = try! JSONEncoder().encode(valueToEncode)
print(String(data: encoded, encoding: .utf8)!)
/* OUTPUT:
{"type":"first","name":"Hello, World!"}
*/
// Decoding
let data = """
[{
"type": "first",
"name": "Test"
}, {
"type": "second",
"number": 10
}]
""".data(using: .utf8)!
let decoded = try! JSONDecoder().decode([TargetEnum].self, from: data)
print(decoded)
/* OUTPUT:
[__lldb_expr_66.TargetEnum.first(__lldb_expr_66.SomeObject(name: "Test")),
__lldb_expr_66.TargetEnum.second(__lldb_expr_66.OtherObject(number: 10))]
*/
@multitudes
Copy link

This is really appreciated. Thank you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment