Search code examples
swiftread-eval-print-loop

How to load javascript files in the swift repl


I would like to load some javascript files into the Swift REPL. How can that be done? My attempt is launching

swift

from a directory containing the javascript files and then executing

import Foundation
let js = "jquery.min"
if let fileURL = Bundle.main.url(forResource: js, withExtension: "js") {
    print("found \(js)")
} else {
    print("Try another day")
}

Naturally we see

Try another day

Is there any way to load resources/files in the REPL?


Solution

  • I have expanded the code as follows:

    import UIKit
    import Foundation
    
    func getResources(_ subDir:String? = nil, _ ext: String? = nil)->[URL]? {
        return Bundle.main.urls(forResourcesWithExtension: ext, subdirectory: subDir)
    }
    
    let furls: String = {
        if let fileURLs = getResources(nil, nil) {
        print(fileURLs)
        return("found \(fileURLs.map{$0.absoluteString}.joined(separator: "\n"))")
    } else {
        return("Try another day")
    }
    }()
    

    The point here is to see exactly what are the files in the playground. Apparently none of the project files are included

    So there would be no way to access the .js files - or any other ones for that matter. This is in contrast to say scala repl that has full access to the enclosing project.

    enter image description here