Skip to content

Commit 283dd5d

Browse files
committed
Don't throw DecodingError if superDecoder doesn't exist
1 parent dc74daf commit 283dd5d

File tree

2 files changed

+43
-2
lines changed

2 files changed

+43
-2
lines changed

Sources/Foundation/JSONDecoder.swift

Lines changed: 24 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -750,11 +750,33 @@ extension JSONDecoderImpl {
750750
}
751751

752752
func superDecoder() throws -> Decoder {
753-
try decoderForKey(_JSONKey.super)
753+
do {
754+
return try decoderForKey(_JSONKey.super)
755+
} catch DecodingError.keyNotFound {
756+
var newPath = self.codingPath
757+
newPath.append(_JSONKey.super)
758+
return JSONDecoderImpl(
759+
userInfo: self.impl.userInfo,
760+
from: .null,
761+
codingPath: newPath,
762+
options: self.impl.options
763+
)
764+
}
754765
}
755766

756767
func superDecoder(forKey key: K) throws -> Decoder {
757-
try decoderForKey(key)
768+
do {
769+
return try decoderForKey(key)
770+
} catch DecodingError.keyNotFound {
771+
var newPath = self.codingPath
772+
newPath.append(key)
773+
return JSONDecoderImpl(
774+
userInfo: self.impl.userInfo,
775+
from: .null,
776+
codingPath: newPath,
777+
options: self.impl.options
778+
)
779+
}
758780
}
759781

760782
private func decoderForKey<LocalKey: CodingKey>(_ key: LocalKey) throws -> JSONDecoderImpl {

Tests/Foundation/Tests/TestJSONEncoder.swift

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -456,6 +456,25 @@ class TestJSONEncoder : XCTestCase {
456456
}
457457
}
458458

459+
func test_notFoundSuperDecoder() {
460+
struct NotFoundSuperDecoderTestType: Decodable {
461+
init(from decoder: Decoder) throws {
462+
let container = try decoder.container(keyedBy: CodingKeys.self)
463+
_ = try container.superDecoder(forKey: .superDecoder)
464+
}
465+
466+
private enum CodingKeys: String, CodingKey {
467+
case superDecoder = "super"
468+
}
469+
}
470+
let decoder = JSONDecoder()
471+
do {
472+
let _ = try decoder.decode(NotFoundSuperDecoderTestType.self, from: Data(#"{}"#.utf8))
473+
} catch {
474+
XCTFail("Caught error during decoding empty super decoder: \(error)")
475+
}
476+
}
477+
459478
// MARK: - Test encoding and decoding of built-in Codable types
460479
func test_codingOfBool() {
461480
test_codingOf(value: Bool(true), toAndFrom: "true")

0 commit comments

Comments
 (0)