我正在尝试从swift类的单例实例中调用一个方法。
这是我的协议:
@objc public protocol MyProtocol: JSExport {
var name: String { get set }
func sum(a:Int, b: Int) -> Int
}
这是我的班级:
private let sharedInstance = MySingleton()
@objc public class MySingleton: NSObject, MyProtocol {
// Singleton
public class var sharedApp : MySingleton {
return sharedInstance
}
public var username: String
override private init() {
self.username = "Oscar"
super.init()
}
public func sum(a: Int, b: Int) -> Int {
return a + b
}
}
我跑了一些测试。当我访问一个属性时,它通过:
func testName() {
var virtualMachine = JSVirtualMachine()
js = JSContext(virtualMachine: virtualMachine)
var singleton: MySingleton = MySingleton.sharedApp
self.context.setObject(
singleton.self,
forKeyedSubscript: "Singleton")
let name = js.evaluateScript("Singleton.username").toString()
XCTAssertTrue(name == "Oscar", "Name is not Colossal, was " + name); // PASS!!!!!
}
然而,当我调用一个方法时,它失败了:
func testSum() {
var virtualMachine = JSVirtualMachine()
js = JSContext(virtualMachine: virtualMachine)
var singleton: MySingleton = MySingleton.sharedApp
self.context.setObject(
singleton.self,
forKeyedSubscript: "Singleton")
let name = js.evaluateScript("Singleton.sum(3, 2);").toInt32()
XCTAssertTrue(sum == 5, "Sum was " + String(sum)); // Fails. Says sum was 0
}
它只适用于从/向Javascript对象读取/写入属性,而不是在调用方法时....
我做错了什么?
答案 0 :(得分:2)
我刚刚找到了解决方案。试试这个。
func sum(a:Int, _ /* <-- make this argument unnamed */ b: Int) -> Int
似乎JSExport
还不支持命名参数。
答案 1 :(得分:1)
JSExport支持命名参数,您只需将它们添加到函数名称,例如:
迅捷功能:
func myFunction(param1 : String, param2 : String, param3 : String)
必须从javascript调用:
myFunctionParam2Param3( "a", "b", "c")
在你的情况下,只需调用sumB()而不是sum():
let name = js.evaluateScript("Singleton.sumB(3, 2);").toInt32()