Running Swift Scripts From The Command Line

 

Swift Scripts From The Command Line

This post updated for Xcode 6.1

One of the great features of swift is it’s ability to be used on the command line. It’s actually really easy to do, and I’ll show you how to make an executable Swift file in this tutorial.

First let’s create a new Swift file. In any text editor, create a new file and save it as Hello.swift.

In order to make this file executable we need to give it permissions. In the terminal app, navigate to your file using the cd command, and then type this:

chmod +x Hello.swift

Now open up your Swift file. We’re going to tell it to use xcrun to run our code.
First, let’s get a simple script going that prints a response to the console:

#!/usr/bin/env xcrun swift

println("Hello World!")

This is great, but what about arguments? It’s very common for a script to take some arguments, do something with them, and then return a result.
Let’s say we wanted to make a command line utility that takes any number of numbers as arguments, and just adds them together. We’ll call it SwiftSum.

A reasonable first step in building this script would be to simply print out the command line arguments. Similar to other languages, Swift automatically creates an argument count variable and argument value pointer.

C_ARGC is the number of arguments passed in
C_ARGV is an array of the argument’s values

We can loop through the arguments and print them fairly easily…

#!/usr/bin/env xcrun swift
for i in 1..<C_ARGC {
  let index = Int(i)
  if let argStr = String.fromCString(C_ARGV[index]) {
    println(argStr)
  }
}
SwiftSum.swift 1 2 3

Outputs:

1
2
3

If we want to add these, we just need to attempt converting them to an Int, and if that succeeds add it to a total…

#!/usr/bin/env xcrun swift

var total : Int = 0

for i in 1..<C_ARGC {
  let index = Int(i)
  if let argStr = String.fromCString(C_ARGV[index]) {
    if let argInt = argStr.toInt() {
      total += argInt
    }
  }
}

println(total)
$ ./SwiftSum.swift 1 2 3

Outputs:

6

In my book I talk more about using Swift from the command line, so I hope you choose to follow along. If not, make sure you subscribe to get the latest tutorials from me.

Follow me on Twitter


Sign up now and get a set of FREE video tutorials on writing iOS apps coming soon.

Subscribe via RSS

4 thoughts on “Running Swift Scripts From The Command Line

  1. I don’t think you tested this out. πŸ˜›

    #!/usr/bin/env xcrun swift -i -sdk /Applications/Xcode6-Beta.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.10.sdk won’t work, you have to move the -i to the end.

Comment