Start scripting in Swift

Recently I have had to analyze a large text file in order to obtain some statistics. I had heard about the possibility of scripting in Swift and because I'm writing Swift code since its beginning, it was natural to also try to use it for scripting.

Here is how I actually get started with scripting in Swift.

Let's start

Swift REPL (Read-Eval-Print-Loop) lets us execute Swift files with a simple command, so all we need to do is:

  1. Create a Swift file.
    touch script.swift
    (You can also use Xcode for that 😉)
  2. Edit the script. For example, you can begin with this usefull and little know line of code: print("Hello, world").
  3. Then, run it.
    swift script.swift

That's it!
To get a little bit fancier, we can add execute permission to the file (chmod +x script.swift) and add the interpreter directive on top of our script file: #!/usr/bin/env xcrun swift. Now we can run the script just like that: ./script.swift.

Arguments

Output only script can be usefull but in most cases we want the script to act diffenrently depending on input parameters. For that, we don't have anything to do, our script automatically accept input from Terminal.

When executing the script, arguments are space-separed values as follow: ./script.swift Argument1 "Argument 2" Argument\ 3. In the script, we can retrieve it from Process.arguments as an array of strings in which the first element is the path of the script file.


That's a first look at how I start writing scripts in Swift. I will post soon about my implementation of script command and subcommand which take advantage of the power of the Swift language.