Creating a command-line application

Swift is useful in creating not only Mobile applications or Mac OSX GUI applications it can be used to also create a commandline application which is run on the Terminal. Let’s start with the simplest/minimalist application. There is an commandline utility called yes. If you write and use bash scripts, then you could have come across and/or have used this utility. If not, all this utility does is stream a series of y to the terminal.

The Original Source Code

If you look at the source of the yes command it is quite simple all it does is puts("y") in an endless loop.

Source: https://opensource.apple.com/source/shell_cmds/shell_cmds-203/yes/yes.c.auto.html

Recreating this in Swift

We shall re-create this in the simplest form, i.e. with the minimalist amount of code.

Getting the Arguments

When you run code at the terminal, an array of parameters are passed to the utility, the first being the name of the application, followed by the arguments separated by spaces.
so if you were to run command one two, then the arguments array would look like

Getting the CommandLine arguments

Swift4 now has an easier way to access the arguments from the commandLine using the code as

and now we can pass this to the main function as

Recapping the entire code

some concerns

In the terminal, if you find the yes utility and look at the size of the same, it is about 17760 bytes in size.If you were to compile the Swift code, the resulting file is about 10MB (Debug Mode) and approximately 6.6 MB for the release version.

You can also run this as a swift bash script file, all you need to do is add a script handler on the firstline of the script and save it. So, the script would look something like,

Next you need to change the permissions for the script file by making them executable, by running the command on the terminal in the same directory as the script file.

and then you can simply call it like you would a compiled utility. The size of the script is approximately 333 bytes given that you have the swift runtime present on your computer. This will also run on a Linux box or even a Windows box if you have installed Swift. Where as the compiled files are platform specific.

Views All Time
Views All Time
112
Views Today
Views Today
1
Posted in Article, Tutorial.