Skip to content

Instantly share code, notes, and snippets.

@akingdom
Last active July 10, 2022 15:21
Show Gist options
  • Save akingdom/72d8c8b3584edabaa51b5dcbadee7772 to your computer and use it in GitHub Desktop.
Save akingdom/72d8c8b3584edabaa51b5dcbadee7772 to your computer and use it in GitHub Desktop.
Example showing how to allow a Swift class to be instantiated via a 'new' in Javascript.
// Swift 5.0 + Javascript
// How to use 'new <classtype>' in Javascript to instantiate a Swift object (from JavaScriptCore).
//
// I couldn't find this clearly documented in any one place.
//
// By Andrew Kingdom
// MIT license
//
@objc
public protocol SampleProtocol: JSExport {
func message(_ text:String)
// static func createSample(_ name:AnyObject) -> Sample
static func create() -> Sample
func initSample() -> Sample // 'new' -- it seems this function name must be init followed by the class name.
}
@objc
open class Sample : NSObject, SampleProtocol {
var old: String = ""
public func message(_ text: String) {
print("---")
print(old)
print(text)
old = text
}
// public static func createSample(_ name: AnyObject) -> Sample {
// return Sample() // i
// }
public static func create() -> Sample {
return Sample()
}
public func initSample() -> Sample {
return self
}
}
class Test {
public static func test() {
if let context = JSContext() {
context.setObject(Sample.self,
forKeyedSubscript: "Sample" as NSString)
context.evaluateScript("""
var sample = new Sample();
sample.message('Hi 🌏');
""")
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment