Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I turn a string into a block of code in swift?

Tags:

ios

swift

Is there any way to turn a string into a block of code? I'm making an Ajax request to a website of mine that has an endpoint that returns some swift code as a string. I can get that code back as a string, but I can't run that code because it doesn't know that it is code.

like image 648
Isaac Wasserman Avatar asked May 05 '15 16:05

Isaac Wasserman


1 Answers

As others have pointed out, if you are creating an iOS app (especially for distribution on the app store), you can not do this. However, if you are writing Swift code for an OS X machine AND you know that XCode is installed on the machine, you can run your Swift code string by running the command-line Swift compiler. Something like this (with proper error checking, of course):

var str = "let str = \"Hello\"\nprintln(\"\\(str) world\")\n"    

let task = Process()

task.launchPath = "/usr/bin/swift"

let outpipe = Pipe()
let inpipe = Pipe()
inpipe.fileHandleForWriting.write(str.data(using: String.Encoding.utf8, allowLossyConversion: true)!)
task.standardInput = inpipe
task.standardOutput = outpipe
task.launch()
task.waitUntilExit()
task.standardInput = Pipe()

let data = outpipe.fileHandleForReading.readDataToEndOfFile()

let output = NSString(data: data, encoding: String.Encoding.utf8.rawValue)! as String

Again, this is probably not recommended in nearly all real-world cases, but is a way you can execute a String of Swift code, if you really need to.

like image 192
Jeff Hay Avatar answered Oct 11 '22 12:10

Jeff Hay