Skip to content

Commit 43e0e4a

Browse files
committed
Fixed strict bool matching in JSONEncoder
1 parent 1b36a51 commit 43e0e4a

File tree

2 files changed

+11
-17
lines changed

2 files changed

+11
-17
lines changed

Foundation/JSONEncoder.swift

Lines changed: 5 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1615,27 +1615,15 @@ extension _JSONDecoder {
16151615
guard let value = value else { return nil }
16161616
guard !(value is NSNull) else { return nil }
16171617

1618-
// if let number = value as? NSNumber {
1619-
// // TODO: Add a flag to coerce non-boolean numbers into Bools?
1620-
// if number === kCFBooleanTrue as NSNumber {
1621-
// return true
1622-
// } else if number === kCFBooleanFalse as NSNumber {
1623-
// return false
1624-
// }
1625-
//
1626-
// /* FIXME: If swift-corelibs-foundation doesn't change to use NSNumber, this code path will need to be included and tested:
1627-
// } else if let bool = value as? Bool {
1628-
// return bool
1629-
// */
1630-
//
1631-
// }
1632-
//
1633-
// throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value)
1634-
16351618
guard let number = value as? NSNumber else {
16361619
throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value)
16371620
}
16381621

1622+
// TODO: Add a flag to coerce non-boolean numbers into Bools?
1623+
guard number._objCType == .Bool else {
1624+
throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value)
1625+
}
1626+
16391627
let bool = number.boolValue
16401628
guard NSNumber(value: bool) == number else {
16411629
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed JSON number <\(number)> does not fit in \(type)."))

TestFoundation/TestJSONEncoder.swift

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -321,6 +321,12 @@ class TestJSONEncoder : XCTestCase {
321321
// MARK: - Test encoding and decoding of built-in Codable types
322322
func test_codingOfBool() {
323323
test_codingOf(value: Bool(true), toAndFrom: "true")
324+
test_codingOf(value: Bool(false), toAndFrom: "false")
325+
326+
do {
327+
_ = try JSONDecoder().decode([Bool].self, from: "[1]".data(using: .utf8)!)
328+
XCTFail("Coercing non-boolean numbers into Bools was expected to fail")
329+
} catch { }
324330
}
325331

326332
func test_codingOfInt8() {

0 commit comments

Comments
 (0)