September 3, 2017

Assigning Swift closure into JSValue object

The closure code to be passed into the JSValue object must have @convention(block) attribute is required. Here is the sample code:.

let closure: @convention(block) (_ value: JSValue) -> JSValue = {
  (_ value: JSValue) -> JSValue in
  /* contents of closure */
... = JSValue(object: closure, in: ctxt)) /* Allocate JSValue */

There is following description in Apples's document about JSValue. But I didn't noticed.

Objective-C blocks (or Swift closures with the @convention(block) attribute) become JavaScript Function objects, with parameter and return types converted using the same rules as values. Converting a JavaScript function backed by a native block or method returns that block or method; all other JavaScript functions convert as empty dictionaries.

The @convention(block) directive is used to generate the closure code which has compatibility with the C object.

No comments: