I'm looking to instantiate a Swift Class in a JavaScriptCore context.
我想在JavaScriptCore上下文中实例化一个Swift类。
I tried different syntaxes with a Playground, also tried on Xcode 6.4 (Swift 1.2) and Xcode 7 beta 3 (Swift 2.0) but no success =-(
我尝试了与Playground不同的语法,也试过Xcode 6.4(Swift 1.2)和Xcode 7 beta 3(Swift 2.0),但没有成功= - (
Maybe I'm missing something.
也许我错过了一些东西。
In the more complex example I found on the net, the protocol 'create' function was defined as a 'class func' but the compiler refuses this syntax telling "Class methods are only allowed within classes; use 'static' to declare a static method"... so I did.
在我在网上找到的更复杂的例子中,协议'create'函数被定义为'class func'但编译器拒绝这种语法告诉“类方法只允许在类中;使用'static'来声明静态方法“... 所以我做了。
Here is my code (OS X 10.10.4 - Xcode 6.4). I use a Playground :
这是我的代码(OS X 10.10.4 - Xcode 6.4)。我用了一个游乐场:
//: Playground - noun: a place where people can play
import Foundation
import JavaScriptCore
let context = JSContext()
// errors handling
context.exceptionHandler = { context, exception in
println("JS Error: \(exception)")
}
@objc
protocol PersonJavaScritMethod : JSExport {
func sayHello()
static func create(name : String) -> Person
}
class Person : NSObject, PersonJavaScritMethod {
var name : String!
init(name:String) {
super.init()
println("# init done #")
self.name = name
}
class func create(name : String) -> Person {
return Person(name: name)
}
func sayHello() {
println("Hello \(name)")
}
}
let aPerson = Person.create("Toto")
// -> ok : console output : "# init done #"
aPerson.sayHello()
// -> ok : console output : "Hello Toto"
context.globalObject.setObject(Person.self, forKeyedSubscript: "Person")
context.evaluateScript("Person.create('Mike')")
// -> not ok : console output :
// "JS Error: TypeError: undefined is not a function (evaluating 'Person.create('Mike')')"
1 个解决方案
#1
1
This is working with XCode 8.2.1 and swift3 (I bet this has to do with new method name/label management in Swift 3):
这适用于XCode 8.2.1和swift3(我打赌这与Swift 3中的新方法名称/标签管理有关):
context.evaluateScript("Person.createWithName('Mike')")
#1
1
This is working with XCode 8.2.1 and swift3 (I bet this has to do with new method name/label management in Swift 3):
这适用于XCode 8.2.1和swift3(我打赌这与Swift 3中的新方法名称/标签管理有关):
context.evaluateScript("Person.createWithName('Mike')")