@@ -20,6 +20,16 @@ final class DecodingTests: XCTestCase {
2020 }
2121 }
2222
23+ struct Account : Equatable {
24+ var id : UUID
25+ var user : User ?
26+
27+ enum CodingKeys : CodingKey {
28+ case id
29+ case user
30+ }
31+ }
32+
2333 func testMap_WithClosure( ) {
2434 XCTAssertEqual (
2535 " test string " ,
@@ -96,6 +106,92 @@ final class DecodingTests: XCTestCase {
96106 XCTAssertEqual ( " Unknown " , user. city)
97107 }
98108
109+ func testDecodingParentChildDecodings( ) throws {
110+ let json = """
111+ {
112+ " id " : " 00000000-0000-0000-0000-000000000001 " ,
113+ " user " : {
114+ " name " : " Joe Bloggs " ,
115+ " age " : 18,
116+ " city " : " London "
117+ }
118+ }
119+ """
120+
121+ let userDecoding = zip ( with: User . init) (
122+ Decoding< String>
123+ . withKey( User . CodingKeys. name) ,
124+
125+ Decoding< Int>
126+ . withKey( User . CodingKeys. age) ,
127+
128+ Decoding< String>
129+ . optionalWithKey( User . CodingKeys. city)
130+ )
131+
132+ let accountDecoding = zip ( with: Account . init) (
133+ Decoding< UUID>
134+ . withKey( Account . CodingKeys. id) ,
135+
136+ userDecoding
137+ . withKey ( Account . CodingKeys. user)
138+ )
139+
140+ let account = try decoder. decode (
141+ json. data ( using: . utf8) !,
142+ as: accountDecoding
143+ )
144+
145+ XCTAssertEqual (
146+ UUID ( uuidString: " 00000000-0000-0000-0000-000000000001 " ) ,
147+ account. id
148+ )
149+
150+ XCTAssertEqual (
151+ User ( name: " Joe Bloggs " , age: 18 , city: " London " ) ,
152+ account. user
153+ )
154+ }
155+
156+ func testDecodingParentChildDecodings_MissingOptionalChildValue( ) throws {
157+ let json = """
158+ {
159+ " id " : " 00000000-0000-0000-0000-000000000001 "
160+ }
161+ """
162+
163+ let userDecoding = zip ( with: User . init) (
164+ Decoding< String>
165+ . withKey( User . CodingKeys. name) ,
166+
167+ Decoding< Int>
168+ . withKey( User . CodingKeys. age) ,
169+
170+ Decoding< String>
171+ . optionalWithKey( User . CodingKeys. city)
172+ )
173+
174+ let accountDecoding = zip ( with: Account . init) (
175+ Decoding< UUID>
176+ . withKey( Account . CodingKeys. id) ,
177+
178+ userDecoding
179+ . optionalWithKey ( Account . CodingKeys. user)
180+ )
181+
182+ let account = try decoder. decode (
183+ json. data ( using: . utf8) !,
184+ as: accountDecoding
185+ )
186+
187+ XCTAssertEqual (
188+ UUID ( uuidString: " 00000000-0000-0000-0000-000000000001 " ) ,
189+ account. id
190+ )
191+
192+ XCTAssertNil ( account. user)
193+ }
194+
99195 // MARK: - Decoding collections
100196
101197 func testDecodingArrayOfSimpleValues( ) throws {
0 commit comments