Closed
Description
Previous ID | SR-12974 |
Radar | None |
Original Reporter | @LucianoPAlmeida |
Type | Bug |
Status | Closed |
Resolution | Invalid |
Attachment: Download
Environment
Xcode 11.5
Additional Detail from JIRA
Votes | 0 |
Component/s | Foundation |
Labels | Bug |
Assignee | None |
Priority | Medium |
md5: 24b93375887ee6f6f34bb2f0a444e4da
Issue Description:
Exemple:
import Foundation
class B: Codable {
var value: Double?
}
class A: Codable {
init(_ value: Double) {
self.a = value
self.b = B()
self.b?.value = value
}
var a: Double?
var b: B?
}
extension Encodable {
var dictionary: [String: Any]? {
let encoder = JSONEncoder()
guard let data = try? encoder.encode(self) else { return nil }
return (try? JSONSerialization.jsonObject(with: data, options: .allowFragments)).flatMap { $0 as? [String: Any] }
}
}
let a = A(20.00)
print(a.dictionary)
When encoding the value, JSONEncoder makes a Double value an Int64 when it doesn't have fractional values.
As seen in the screenshot bellow, the encoder uses the double type when it has fractional part

But when encoding a value that doesn't have a fractional part it losses type information and encode the value as Int64.

The question is if that is intended behavior (optimization) or is indeed a problem? If that is intended behavior is fine because at the end it represents the same value, but I'm just a bit curious to know why the encoder does that 🙂