Ebrahim Tahernejad Ebrahim Tahernejad - 28 days ago 13
Objective-C Question

Is it possible in Objective-C to execute Swift code from a string?

I've seen a learning app doing this.

It runs the swift code inside the iOS app. so I downloaded the swift's source code and now I don't know what should I do next.

it's completely different from something like bridge ... the user must write the code ... not me ...
for example in python we can use it's library to run a command given as string:

#include <Python.h>

int main(int argc, char *argv[]) {
Py_SetProgramName(argv[0]); /* optional but recommended */
Py_Initialize();
PyRun_SimpleString("from time import time,ctime\n"
"print 'Today is',ctime(time())\n");
Py_Finalize();
return 0;
}


now I'm searching for something like:
SwiftRun_SimpleString("print(\"Hello!\")");

Answer

What you are asking is how to run or interpret Swift code that is provided at run time, like the Swift command-line REPL or the iPad's Swift Playgrounds app. The full answer is really much too complicated for stackoverflow.

You'll need to use the Swift compiler source code to do this. Start by looking at swift-lldb (the version of the llvm project's debugger with Swift support), which does what you're describing.

Comments