0

I am trying to get a JavaScript function reference in Swift and execute it.

Initially, I used arrow function in JS side, my JavaScript function is like this.

const invokeCallback = (cbID, args) => {   
    // do some stuff
}

And in the Swift side, i use objectForKeyedSubscript in JSContent to get the property invokeCallback in the context’s global object.

    context?.evaluateScript(jsCodeContent)
    let invoke: JSValue? = context?.objectForKeyedSubscript("invokeCallback")
    
    guard let invokeCallback = invoke else { return }
    guard !invokeCallback.isUndefined else { return }
        
    invokeCallback.call(withArguments: [cbId, args])

But I can't it turns out the result is undefined.

Printing description of invoke:
▿ Optional<JSValue>
  - some : undefined

Then, I tried this syntax to define the function.

function invokeCallback(cbID, args) {
}

I can retrieve the function in Swift side now

Printing description of invokeCallback:
function invokeCallback(cbID, args) {
   // ....
}

Do someone know why the first case doesn't work while the second one work? Kindlyshare this knowledge to me? thanks

Ref:

RY_ Zheng
  • 3,041
  • 29
  • 36

1 Answers1

1

The issue isn't the arrow function, but the way you declare your function.

Functions declared with a function declaration that are in the global context, become part of the global object.

Variables that are declared with var in the global context also become part of the global object. In that case it doesn't matter whether you assign an (arrow) function expression or any other value.

Variables declared with const in the global context do not become part of the global object.

Because your arrow function is assigned to a variable that is declared with const, it is not part of the global object and so you cannot find it. If you want your function to become part of the global object, you should either use a function declaration, declare your variable with var, or assign it directly to the global object.

globalThis.invokeCallback = () => {...};

It is also worth noting that arrow functions and regular function expression (not to be confused with function declarations) are not always interchangeable.

Ivar
  • 6,138
  • 12
  • 49
  • 61