I want to instantiate a Swift class in the context of a JavaScriptCore.
I tried different syntaxes with the playground, and also tried to use Xcode 6.4 (Swift 1.2) and Xcode 7 beta 3 (Swift 2.0), but without success = - (
Maybe something is missing for me.
In a more complex example that I found on the network, the protocol's “create” function was defined as a “func class”, but the compiler rejects this syntax, saying: “Class methods are allowed only in classes, use“ static ”to declare a static method" ... so what I did.
Here is my code (OS X 10.10.4 - Xcode 6.4). I am using Playground:
import Foundation
import JavaScriptCore
let context = JSContext()
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")
aPerson.sayHello()
context.globalObject.setObject(Person.self, forKeyedSubscript: "Person")
context.evaluateScript("Person.create('Mike')")
source
share