generated from TBD54566975/tbd-project-template
-
Notifications
You must be signed in to change notification settings - Fork 2
/
FlatMap.swift
34 lines (29 loc) · 996 Bytes
/
FlatMap.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
import AnyCodable
import Foundation
/// Wrapper used to easily encode a `[String: AnyCodable]` to and decode a `[String: AnyCodable]` from a flat map.
@propertyWrapper
struct FlatMap: Codable {
var wrappedValue: [String: AnyCodable]?
init(wrappedValue: [String: AnyCodable]?) {
self.wrappedValue = wrappedValue
}
init(from decoder: Decoder) throws {
let value = try decoder.singleValueContainer()
if let mapValue = try? value.decode([String: AnyCodable].self) {
wrappedValue = mapValue
} else {
throw DecodingError.typeMismatch(
FlatMap.self,
DecodingError.Context(
codingPath: decoder.codingPath, debugDescription: "TODO"
)
)
}
}
func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
if let wrappedValue {
try container.encode(wrappedValue)
}
}
}