5 June 2016 1min read

Poor man's hot reloading for Swift scripts

The other day, while I was writing a Swift script, I added an option to make it run continuosly so it could be on a server doing its job without stoping. for eva.

To implement that I just used a repeat loop creating NSTasks that called the same script. Scripts recursion.

The funny part is that with this simple thing I found a quick way to writing the script, almost as a hot reloading tool.

let reload = “reload”if Process.arguments.contains(reload) {repeat {let task = NSTask()task.launchPath = Process.arguments.first!task.arguments = Array(Process.arguments.suffixFrom(1).filter({$0 != reload}))task.launch()task.waitUntilExit()} while true}

Just drop this snippet at the top of the script, and when you call it with the reload argument it will start looping indefinitely.

Then you can just call it from the command line like:

main.swift reload other params

When that is done you can just modify the script and save the file, in the next execution your changes will be visible. If it fails to compile is not a big deal, the main script is still in memory without those changes so it will just loop and try to run it again.

Obviously is not a big deal, is a bit annoying seeing all the console spammed, but I found it quite useful while I’m developing short scripts that I want to iterate on.

Remember that you can use OS signals to stop the task when the main script is killed.

If you enjoyed this post

Continue reading