Isaac Wasserman
Isaac Wasserman

Reputation: 1541

Can I turn a string into a block of code in 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.

Upvotes: 7

Views: 4031

Answers (2)

Duncan C
Duncan C

Reputation: 131418

No, you can't do that. Swift is a compiled language, not interpreted like Ajax.

The Swift compiler runs on your Mac, not on the iOS device. (The same is true for Objective-C).

Plus, Apple's app store guidelines forbid delivering executable code to your apps, so even if you figured out a way to do it, your app would be rejected.

Edit:

Note that with the advent of Swift playgrounds, it is possible to run the Swift compiler on an iPad. Recent high-end iPhones are probably also up to the job, but you'd have to figure out how to get it installed.

As stated above though, Apple's app store guidelines forbid you from delivering code to your apps at runtime.

Upvotes: 14

Jeff Hay
Jeff Hay

Reputation: 2645

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.

Upvotes: 18

Related Questions