Skip to content

Instantly share code, notes, and snippets.

@theoriginalbit
Forked from donnywals/Associated.swift
Last active February 22, 2021 22:56
Show Gist options
  • Save theoriginalbit/2946199e8dd70dbffb0d39aa439aa944 to your computer and use it in GitHub Desktop.
Save theoriginalbit/2946199e8dd70dbffb0d39aa439aa944 to your computer and use it in GitHub Desktop.
import Foundation
enum TargetEnum: Decodable {
case first(SomeObject)
case second(OtherObject)
enum CodingKeys: CodingKey {
case type
}
enum Unassociated: String, Decodable {
case first
case second
}
var unassociated: Unassociated {
switch self {
case .first:
return .first
case .second:
return .second
}
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
let type = try container.decode(Unassociated.self, forKey: .type)
switch type {
case .first:
try self = .first(SomeObject(from: decoder))
case .second:
try self = .second(OtherObject(from: decoder))
}
}
}
struct SomeObject: Decodable {
let name: String
}
struct OtherObject: Decodable {
let number: Int
}
let data = """
[{
"type": "first",
"name": "Test"
}, {
"type": "second",
"number": 10
}]
""".data(using: .utf8)!
let decoded = try! JSONDecoder().decode([TargetEnum].self, from: data)
print(decoded)
print(decoded.filter { $0.unassociated == .first })
/* OUTPUT:
[__lldb_expr_66.TargetEnum.first(__lldb_expr_66.SomeObject(name: "Test")),
__lldb_expr_66.TargetEnum.second(__lldb_expr_66.OtherObject(number: 10))]
[__lldb_expr_1.TargetEnum.first(__lldb_expr_1.SomeObject(name: "Test"))]
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment