Skip to content

Commit 7a5612d

Browse files
committed
Add decoderForKeyNoThrow
1 parent 283dd5d commit 7a5612d

File tree

2 files changed

+22
-24
lines changed

2 files changed

+22
-24
lines changed

Sources/Foundation/JSONDecoder.swift

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

752752
func superDecoder() throws -> Decoder {
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-
}
753+
return decoderForKeyNoThrow(_JSONKey.super)
765754
}
766755

767756
func superDecoder(forKey key: K) throws -> Decoder {
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-
}
757+
return decoderForKeyNoThrow(key)
780758
}
781759

782760
private func decoderForKey<LocalKey: CodingKey>(_ key: LocalKey) throws -> JSONDecoderImpl {
@@ -792,6 +770,25 @@ extension JSONDecoderImpl {
792770
)
793771
}
794772

773+
private func decoderForKeyNoThrow<LocalKey: CodingKey>(_ key: LocalKey) -> JSONDecoderImpl {
774+
let value: JSONValue
775+
do {
776+
value = try getValue(forKey: key)
777+
} catch {
778+
// if there no value for this key then return a null value
779+
value = .null
780+
}
781+
var newPath = self.codingPath
782+
newPath.append(key)
783+
784+
return JSONDecoderImpl(
785+
userInfo: self.impl.userInfo,
786+
from: value,
787+
codingPath: newPath,
788+
options: self.impl.options
789+
)
790+
}
791+
795792
@inline(__always) private func getValue<LocalKey: CodingKey>(forKey key: LocalKey) throws -> JSONValue {
796793
guard let value = dictionary[key.stringValue] else {
797794
throw DecodingError.keyNotFound(key, .init(

Tests/Foundation/Tests/TestJSONEncoder.swift

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1500,6 +1500,7 @@ extension TestJSONEncoder {
15001500
("test_encodingNonConformingFloatStrings", test_encodingNonConformingFloatStrings),
15011501
("test_nestedContainerCodingPaths", test_nestedContainerCodingPaths),
15021502
("test_superEncoderCodingPaths", test_superEncoderCodingPaths),
1503+
("test_notFoundSuperDecoder", test_notFoundSuperDecoder),
15031504
("test_codingOfBool", test_codingOfBool),
15041505
("test_codingOfNil", test_codingOfNil),
15051506
("test_codingOfInt8", test_codingOfInt8),

0 commit comments

Comments
 (0)