Created
August 26, 2018 06:13
-
-
Save joshuajhomann/e6fd6f66f76c0b18cff9f09d8811137e to your computer and use it in GitHub Desktop.
This file contains 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 Test: Codable { | |
let items: [HeterogeneousType] | |
} | |
struct HeterogeneousType: Codable { | |
let id: ID | |
var sample: Data { | |
return """ | |
{ | |
"items": [ | |
{ | |
"id": 1 | |
}, | |
{ | |
"id": "UUID" | |
} | |
] | |
} | |
""".data(using: .utf8)! | |
} | |
} | |
enum ID: Codable { | |
case id(Int) | |
case uuid(String) | |
init(from decoder: Decoder) throws { | |
let container = try decoder.singleValueContainer() | |
if let id = try? container.decode(Int.self) { | |
self = .id(id) | |
return | |
} else if let uuid = try? container.decode(String.self) { | |
self = .uuid(uuid) | |
return | |
} | |
throw DecodingError.typeMismatch(ID.self, DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Wrong type for ID")) | |
} | |
func encode(to encoder: Encoder) throws { | |
var container = encoder.singleValueContainer() | |
switch self { | |
case .id(let id): | |
try container.encode(id) | |
case .uuid(let uuid): | |
try container.encode(uuid) | |
} | |
} | |
} |
This file contains 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
//: Playground - noun: a place where people can play | |
import UIKit | |
struct Safe<Decoded: Decodable>: Decodable { | |
let value: Decoded? | |
init(from decoder: Decoder) throws { | |
do { | |
let container = try decoder.singleValueContainer() | |
value = try container.decode(Decoded.self) | |
} catch { | |
#if DEBUG | |
fatalError(error) | |
#else | |
print(error) | |
#endif | |
self.value = nil | |
} | |
} | |
} | |
struct Dog: Codable { | |
var name: String | |
var id: Int | |
var sample: Data { | |
return """ | |
[{ | |
"id" : 1, | |
"name" : "Fluffy" | |
}, | |
{ | |
"id" : 2, | |
"Name" : "Rover" | |
}] | |
""".data(using: .utf8)! | |
} | |
} | |
do { | |
let dogs = try JSONDecoder().decode([Safe<Dog>].self, from: Dog.sample).compactMap { $0.value } | |
print(String(describing: dogs)) | |
print(type(of: dogs)) | |
} catch { | |
print(error) | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment