Matvii Hodovaniuk

JavaScript.swift

February 02, 2019

How to make importing JavaScript package in Swift easier?

Check the code

What problem does JavaScript.swift solve?

I work mostly with JavaScript and using packages from npm is common solution for faster idea prototyping. It is quite hard to not find package for your problem on npm.

I tried Swift for last two months and found that amount of ready to use solutions in Swift package managers is smaller than in npm.

npm has a lot of packages that can be used for free and easy to install. Swift is a powerful and intuitive programming language that can be run on both Apple’s devices and Linux.

In Swift 5.0 we’ll see @dynamicCallable implemented, which previously helped calling Python from Swift and runing Jupyter notebook.

I wonder if it will be good to have same with JavaScript. I found that JavaScriptCore helps executing JavaScript inside apps for Apple platforms.

I just want to make import a little bit easier.

This solution would look like this:

import JavaScriptCore
let jsSource = """
  var testFunct = function(message) {
     return \"Test Message: \" + message;
  }
"""
var context = JSContext()
context?.evaluateScript(jsSource)
let testFunction = context?.objectForKeyedSubscript("testFunct")
let result = testFunction?.call(withArguments: ["the message"])
// result would be Test Message: the message.

Yeah, look nice. But it would be good to have some sort of import or require to fast import and use.

Like this one:

// here `arr-diff` will return difference between two passed arrays
let arrDiff = import(“arr-diff”)
let diff = arrDiff([1, 2], [2, 3])
// diff will hold array of difference and will be equal to `[1, 3]`

*arr-diff

What we can have right now?

JavaScript.Swift provides an API to import JS code. We need a simple working bridge. Use it to import JavaScript code.


Example:

import JavaScriptSwift

let context = JavaScriptSwift()
try context.importSafe("""
var swiftLib = {
    name: "JavaScript.swift",
    organizers: [
        {
            name: "Matvii",
            twitter: "@hodovani",
            email: "matvii@hodovani.uk"
        },
        {
            name: "Max",
            twitter: "@maxdesiatov",
            email: "max@desiatov.com"
        }
    ]
};
""")

var conference = context.swiftLib.name
// conference will be "JavaScript.swift"

This import will work only for one file package but it can be improved in future. See more examples here

What’s the future roadmap?

In future we will have:

  • The import that we need.
  • The import that will allow us to call methods from npm package. And give ability to import any package from npm

Summary

It was interesting to me to dive into the Swift world. I plan to learn more and share with you.

Please leave feedback on:

Thanks, Max for code review and inspiration


Matvii Hodovaniuk

Personal blog by me