I'm looking to instantiate a Swift Class in a JavaScriptCore context.
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 =-(
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.
Here is my code (OS X 10.10.4 - Xcode 6.4). I use a Playground :
//: 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')')"