Javascript Object native swift type equivalent , JavascriptCore bridging

Hi, i'm currently working with JavascriptCore framework and the bridging with Swift objects.

This framework currently exposes a few bridging methods, but one very quickly hit a wall as there's no equivalent to "json representable value". (the type JSValue defined in the JavascriptCore framework is much wider than that and has to be associated with a JSContext, which makes it unsuitable for regular model).

As a consequence, one has to rely on using NSDictionnary as a generic-enough type, but this feels really clunky, and forces you at some point to use an unhealthy mix of JSONEncoder for when you can know the type at compile-time, and JSONSerialization.dataObject(with)…

All in all, i feel like all the problem stems from the fact the swift stdlib doesnt define something like that :

Am i missing something ?

Even if you did have a JSON enum in the standard library, it wouldn't really be appropriate to use it throughout your code.

Treat JavascriptCore like any other external system like a File system, Database, Network API, message queue, etc. At the boundary layer, take whatever representation your external system uses (SQL rows, JSON blobs, raw file Data, etc.) and parse it into your strongly typed Swift models. Write all your business logic to operate with those. If you need to send data base to these external systems, encode your models back into the representation those systems expect.

When you do that, you'll find that your JSON dictionaries stay contained in a really narrow boundary layer of your system, and don't creep into your whole codebase. The need for a dedicated JSON type drastically reduces from that.


That's what i ended up doing.
Javascript Core lets you export your native Swift types into the JSContext using JSExport protocol. It may look convenient at first because you can then "transparently" use your swift types in javascript. However this hits walls pretty quickly, as you can easily end up with a mix of NSDictionary and your own native swift objects.
In the end i ended up working with NSDictionaries only.

However, from a dependency point of view, this is a bit of a pity. I would have hoped JavascriptCore didn't have to rely on the objective-C runtime, and as a consequence make MY code rely on the objc runtime as well... In theory, all it needs to expose are types defined in the Javascript specification and nothing else.