Swift
Swift
Call a JavaScript Function Returning a Boolean
See more JavaScript Examples
Demonstrates how to call a JavaScript function that returns a boolean.Chilkat Swift Downloads
func chilkatTest() {
var success: Bool = false
// This is the JavaScript function we'll call:
// function isEven(number) {
// return number % 2 === 0;
// }
let sbScript = CkoStringBuilder()!
sbScript.append(value: "function isEven(number) { return number % 2 === 0; }")
let js = CkoJs()!
let result = CkoJsonObject()!
result.emitCompact = false
// Call Eval to add the function to the context's global object
success = js.eval(jscript: sbScript, result: result)
if success == false {
// Examine the result for an exception.
print("\(result.emit()!)")
// Also examine the LastErrorText.
print("\(js.lastErrorText!)")
return
}
// ------------------------------------------------------------------------------
// Call the function isEven(8)
let funcCall = CkoJsonObject()!
// Create JSON specifying the function name and arguments
// {
// "name": "isEven",
// "args": [ 8 ]
// }
funcCall.updateString(jsonPath: "name", value: "isEven")
funcCall.updateInt(jsonPath: "args[0]", value: 8)
success = js.callFunction(func: funcCall, result: result)
if success == false {
// Examine the result for an exception.
print("\(result.emit()!)")
// Also examine the LastErrorText.
print("\(js.lastErrorText!)")
return
}
print("\(result.emit()!)")
// Output:
// {
// "type": "bool",
// "value": true
// }
var retval: Bool = result.bool(of: "value")
print("\(retval)")
// Output:
// true
}