June 5, 2016 🕐 1 min read

- Scripting
- Swift
- Tips and Tricks

# 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 `NSTask` s 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.

- Share this article on Twitter

If you liked this article please consider supporting me

Buy me a coffee

## Continue reading

## Similar suggested articles

- Based on tag Swift

  # Backport SwiftUI modifiers

  October 20, 2023

- Based on tag Scripting

  # Swift script to export lists from Reminders.app

  May 8, 2019

- Based on tag Tips and Tricks

  # Swift Collection's prefix for quick tests

  March 16, 2019

## Or check out this article tags

- Scripting
- Swift
- Tips and Tricks