5

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')')"
3
  • 2
    I tried the same code in a command line application instead of a Playgroud and it works ==> maybe a Playground bug / limitation ? Commented Jul 24, 2015 at 22:13
  • 2
    It also works if I put the protocol and class declaration in a separate file in the Sources folder of the PlayGround, adding "public" before "class Person", "class func create" and "func sayHello", and delete "@objc (Person)" Commented Jul 24, 2015 at 22:27
  • Tnx, saved my time. As you mentioned it is only a playground bug. Commented Apr 21, 2016 at 9:43

1 Answer 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):

context.evaluateScript("Person.createWithName('Mike')")
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.