Swift Script and Command Line Arguments

Filed Under: Swift
swift-script-project-type-command-line

In this tutorial, we’ll discuss how to create Scripts in Swift. Yes, Swift is a scripting language.
We’ll build swift script and run them from the command line while also passing arguments.

Swift Scripts

Apple has restricted Swift to for only building apps or to use it only on XCode. We can use Swift to run scripts from the terminal. We can also write a swift file outside XCode and compile it using the terminal.

A script is just a code that is interpreted on the fly whereas compiled codes are converted into an executable binary to run.

Creating a Swift Script

Note: You can write the following code using any editor and save it with the .swift extension.
We’re using XCode Command Line Project just to use the autocompletion features in our code.

swift script project type command line

Set the project name from the next screen. You’re main.swift file is ready with Foundation Framework set in the import statement. We’ll use Cocoa Framework in our code since it contains the Application Kit alongside Foundation framework too.(Our cool scripts would have something to do with applications).

To make a Swift Script our first line should be shebang as shown below.


#!/usr/bin/env xcrun swift

shebang syntax begins with a # in scripts and is used to invoke our environment(Swift in this case) and to get the script running on the Linux Operating System.

Code

The below script is used to launch the application specified.


#!/usr/bin/env xcrun swift

import Cocoa

var myWorkspace = NSWorkspace.shared
myWorkspace.launchApplication("Android Studio")

NSWorkspace.shared returns an instance of the current workspace on your macbook.
launchApplication is used to launch the application specified.

Running the Script

To run the script we need to first make it executable.
Fire up your Terminal and run the chmod +x command on the Swift file.


chmod +x /path/to/your/file/main.swift

Now to run the script just run the file from the path.


/path/to/your/file/main.swift

Since we’d specified Android Studio, in our case Android Studio gets launched as shown below.

swift scripting example

Handling Command Line Arguments

We can pass the commands after the main.swift.
main.swift is considered as the first argument
To get the arguments in our code, we use the following methods


CommandLine.argc

This returns the count of arguments. An Integer.
The below command returns the String array of arguments entered.


CommandLine.arguments //Array of Strings

CommandLine.arguments[0] //main.swift is the first argument.

Launching Multiple Applications From the Script

Now let’s improve our script such that it launches multiple applications.
A different set of applications would be launched based on the argument name entered.
In our following swift script, we’ll create two Swift Arrays.
The first would contain a custom set of applications that are work related.
The second array would be read related.
We’ll store them in a Swift Dictionary with the keys as work and read respectively.

Our main.swift file code is given below.


#!/usr/bin/env xcrun swift

import Cocoa

var count = CommandLine.argc

print("Number of arguments is \(count)")

var workMode : Array = ["Android Studio", "XCode"]
var readMode : Array = ["Google Chrome", "Notes","iBooks","A"]
var myDictionary = [String: Array<String>]()

myDictionary["work"] = workMode
myDictionary["read"] = readMode


if count > 1
{
    
let key = CommandLine.arguments[1]
    
let apps = myDictionary[key]
if apps?.count != nil{
let myWorkspace = NSWorkspace.shared
    for s in apps! {
myWorkspace.launchApplication(s)
}
}
else{
    print("Incorrect command")
    }
}
else{
   print("Missing command")
}

Our output returned when the script is run on the terminal is given below:
swift script command line arguments

Notice that the workMode array applications are launched. Android Studio and XCode.

That’s all for a short introduction of Swift scripting tool.

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages