Json literal type checking #43
Merged
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
This changes the handling of JSON literals to force dictionary and array values to conform to a new
JSONConvertibleprotocol.This is also adds support for a non-optional initializer since it's known to safely convert.
The resulting JSON objects will be strongly typed and evaluated by the compiler.
They will have more guarantees than something like
JSON([String: Any])which lazily evaluates its children.Performance
It will have a minor impact on performance in so far as the compiler can choose to do one of several things:
The simple array could be compiled as:
The complex array could be
Depending on what the compiler decides to create, it may cost need it iterate and convert an array of primitives into a usable actual object.
This would cost extra allocations and runtime performance.
As long as we aren't creating massive JSON payloads, this shouldn't really be a problem.
Further, you could help the compiler by doing
[1, "a"] as JSONThe alternative would be for Dictionary and Array to only conform to
JSONConvertibleif their values are JSON (as opposed toJSONConvertible.That would mean that literal JSON types (at the second level) would only accept
JSONinstead ofJSONConvertible.That would force each tier of the structure to proactively convert to JSON; however, that means you can't add non-literal values to your array / dictionary.
You would be forced to do something like: