Skip to content

General-purpose value bridging and JSON support #509

@sliemeobn

Description

@sliemeobn

BridgeJS supports passing structs and classes around from and to JS as long as function stubs were generated (derived from .d.ts types).

It will be very useful to drive this feature completely out of Swift code, and convert to and from JS values at will for "general-purpose" APIs.

This will allow us to write Swift-only code that can use the JSON.parse and JSON.stringify from annotated Swift structs.

roughly like:

@JS struct MyState {
  var text: String
  var number: Int?
}

let value: JSString = try? JSON.stringify(MyState(text: "hello"))
localStorage.setItem("my-item", value)

if let item = localStorage.getItem("my-item"),
  let state = try? JSON.parse(item, as: MyState.self)
{
  print("Read my state \(state)" 
}

Essentially, there should be an easy way for Swift types (value and reference types) to get a init(fromJSValue:) and a .toJSValue() or similar.
IIUC for classes, a "backed by JSObject" mechanism exists, and the JSBridge functionally to copy over JS values into a struct exist as well.

Important caveats:

  • reference types can have JSObject backing -> memory stays is JS-land and does not have to be copied
  • value types (structs, enums) -> JSObject backing would break this, suggestion: always copy value over into "clean" swift type
  • non-copyable structs could use JS backing? is that even preferred?

Sub-issues

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions