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

Is there a way to turn a string into a block of code? I am making an Ajax request to my site that has an endpoint that returns some quick code as a string. I can return this code as a string, but I cannot run this code because it does not know that this is code.

+6
source share
2 answers

No, you cannot do this. Swift is a compiled language that is not interpreted as Ajax.

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

In addition, Apple application storage rules prohibit the delivery of executable code to your applications, so even if you figure out how to do this, your application will be rejected.

+10
source

As others noted, if you are creating an iOS application (especially for distribution in the app store), you cannot do this. However, if you are writing Swift code for an OS X machine And you know that Xcode is installed on your computer, you can run the Swift code line by running the Swift compiler from the command line. Something like this (with correct 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 almost all real cases, but it is the way you can execute the String of Swift code if you really need to.

+10
source

Source: https://habr.com/ru/post/986585/


All Articles