- 
                Notifications
    
You must be signed in to change notification settings  - Fork 18
 
Various extensions to JSONValue #68
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Conversation
          Codecov Report
 @@            Coverage Diff             @@
##             main      #68      +/-   ##
==========================================
+ Coverage   85.91%   86.19%   +0.28%     
==========================================
  Files          13       13              
  Lines        1271     1355      +84     
==========================================
+ Hits         1092     1168      +76     
- Misses        179      187       +8     
 Continue to review full report at Codecov. 
  | 
    
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I would like these convenience accessors, but I would be very careful with the implementation of Codable for JSONValue. Especially the JSON number will only be lossy encoded and decoded.
| case .number(let n): | ||
| if let int = self.intValue { | ||
| try container.encode(int) | ||
| } else if let double = self.doubleValue { | 
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Unfortunately, I think this might introduce rounding errors. Because JSON represents numbers as String, you might loose precision when converting to Double and then back to String. Unfortunately, I don't think there is an elegant way to avoid floating point arithmetic when going through the Codable interface.
| let container = try decoder.singleValueContainer() | ||
| if let int = try? container.decode(Int.self) { | ||
| self = .number(String(int)) | ||
| } else if let double = try? container.decode(Double.self) { | 
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Same for the decoding: going through a floating point number can introduce artifacts from floating point arithmetic.
This PR adds the following extensions to the
JSONValueenum:ExpressibleByXLiteralprotocols (so e.g.let x: JSON = ["y": [ "z": [1, 2.2, false]]]is possible)Codableprotocol (if you want a loosely typed value as part of yourCodablestruct, for example)