-
Notifications
You must be signed in to change notification settings - Fork 104
/
DecodingContainerTests.swift
106 lines (82 loc) · 2.78 KB
/
DecodingContainerTests.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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
//
// DecodingContainerTests.swift
// XMLCoderTests
//
// Created by Vincent Esche on 12/26/18.
//
import XCTest
@testable import XMLCoder
private struct Foo: Codable {
var keyedFooBar: String
var keyedFooBaz: String
var unkeyedBar0: String
var unkeyedBar1: String
var unkeyedBar2: String
var unkeyedBar3: String
var singleBlee: String
init(foo: [String: String], bar: [String], blee: String) {
keyedFooBar = foo["bar"]!
keyedFooBaz = foo["baz"]!
unkeyedBar0 = bar[0]
unkeyedBar1 = bar[1]
unkeyedBar2 = bar[2]
unkeyedBar3 = bar[3]
singleBlee = blee
}
enum FooCodingKeys: String, CodingKey {
case bar
case baz
}
enum CodingKeys: String, CodingKey {
case foo
case bar
case blee
}
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
var fooContainer = container.nestedContainer(
keyedBy: FooCodingKeys.self,
forKey: .foo
)
try fooContainer.encode(keyedFooBar, forKey: .bar)
try fooContainer.encode(keyedFooBaz, forKey: .baz)
var barContainer = container.nestedUnkeyedContainer(forKey: .bar)
try barContainer.encode(unkeyedBar0)
try barContainer.encode(unkeyedBar1)
try barContainer.encode(unkeyedBar2)
try barContainer.encode(unkeyedBar3)
try container.encode(singleBlee, forKey: .blee)
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
let fooContainer = try container.nestedContainer(
keyedBy: FooCodingKeys.self,
forKey: .foo
)
keyedFooBar = try fooContainer.decode(String.self, forKey: .bar)
keyedFooBaz = try fooContainer.decode(String.self, forKey: .baz)
var barContainer = try container.nestedUnkeyedContainer(forKey: .bar)
unkeyedBar0 = try barContainer.decode(String.self)
unkeyedBar1 = try barContainer.decode(String.self)
unkeyedBar2 = try barContainer.decode(String.self)
unkeyedBar3 = try barContainer.decode(String.self)
singleBlee = try container.decode(String.self, forKey: .blee)
}
}
final class DecodingContainerTests: XCTestCase {
func testExample() throws {
let foo = Foo(
foo: [
"bar": "BAR",
"baz": "BAZ",
],
bar: ["BAR0", "BAR1", "BAR2", "BAR3"],
blee: "BLEE"
)
let encoder = XMLEncoder()
encoder.outputFormatting = .prettyPrinted
let encoded = try encoder.encode(foo, withRootKey: "foo")
let decoder = XMLDecoder()
_ = try decoder.decode(Foo.self, from: encoded)
}
}