Advertisement
  1. Computer Skills
  2. Swift
Computers

Alfred Workflows in Swift

by
Difficulty:IntermediateLength:LongLanguages:

Apple created a new language to supplement Objective-C: Swift. Swift is still in the C language class, but has some features of an interpreted language. The simpler syntax compared to Objective-C will make learning and using it much easier. Swift is usable as an interpreter or a compiler.

I’m introducing this language by showing how to use it with Alfred Workflows and I assume that you're already familiar with writing workflows in Alfred. If not, please check out these tutorials: Alfred for Beginners, Intermediates, Advanced, and Alfred Debugging.

This tutorial focuses on using Swift with Alfred and not a complete language reference. There is a great tutorial series about learning Swift on Code Tuts+, An Introduction to Swift: Part 1 and An Introduction to Swift: Part 2. I will assume that you have read these articles already.

Installing Xcode 6.1

To install Swift on a Mac, you have to install XCode from the App Store. Once installed, you need to open a terminal window and run:

xcode-select -s /Applications/Xcode.app/ --install

That will make all the XCode tools available to the command line.

Adding Swift to the Shell

You can compile and experiment with Swift in XCode 6.1 and it’s Playground. This tutorial focuses on using Swift on the command line using only a programmer’s editor and the command line.

Assuming you installed XCode 6.1 to the Applications folder, you will need to add Swift’s executables directory to the path. For Bash, add this to your ~/.bashrc file:

For Zsh, add the same line to your ~/.zshrc file. For Fish shell, add this line:

I have found that using the xcrun command without having the PATH set as above does not always work.

To compile Swift files on the command line, you type:

To run Swift in an interactive interpreter, you type:

Adding Swift to an Editor

Adding Swift support for Sublime Text is easy. Install Package Manager for Sublime Text. Once you have Package Manager, you need to install the package Swift by using Shift-Command-P, type package install, enter, and Swift. This should install the Swift package.

On Emacs, the package manager for Emacs is the best route, but it is only in Emacs 24+. For Emacs 24+, you need to download and install Aquamacs. The Emacs installed on a standard Mac is version 22. To install Aquamacs using HomeBrew and HomeBrew Cask, type this in a terminal:

Once installed, you have to add this to your ~/.emacs file:

Run Aquamacs and open the Emacs Package Manager with Meta-x package-list-packages.

Emacs Package Manager
Emacs Package Manager

Look for swift-mode and click it. You might need to install flycheck as well.

For Vim, you need to install Swift.Vim. The easiest way to install Swift.Vim is to install maximum-awesome first. To install maximum-awesome, open a terminal in to the ~/Documents (or any other directory. It has to be some where you plan to keep.). Type the following:

The install will take a while. Afterwards, add this line to your ~/.vimrc.bundle.local file:

Once saved, rerun Vim and type

Vundle, which maximum-awesome installs, will install any new plugins.

Vundler Installing SwiftVim
Vundler Installing Swift.Vim

In this case, Vundler installs the Swift.Vim plugin. Vim will now do syntax highlighting for Swift.

Swift Interpreted vs Compiled

Swift can run as an interpreter or a compiler. To illustrate that, create a file hello.swift and add this to it:

This is the most basic hello world program that people use as their first program. The first line tells the shell you want to run this script using xcrun with the command line specified. xcrun is a Mac OSX program for running XCode utilities from the command line.

Save the file and change it’s execution mode with

Run the file with

And it will produce Hello World! on the terminal by running the script with Swift as an interpreter. To compile, type this on the terminal:

A hello program now exists in that directory. Type

and you will see the exact same output.

Hello World Program
Hello World Program

Both methods produced the exact same result. The only thing different is that for the interpreted approach, XCode 6 has to be on every system that runs it. If you compile the program, it can be ran on any Mac.

An interesting note about the interpreted approach is that it is the same as the compiled approach for what gets ran. In interpreted mode, it compiles the program in memory and runs directly in memory. The compiled approach compiles to disk and you run the program. Overall, you do not save any time by interpreting Swift code.

Alfred Library

To make writing programs for use in Alfred, a library of helper functions can be a great asset. Create a new file called Alfred.swift and place this code inside:

This is a port of my Alfred go language library that I use in the tutorial Track Project Time With Alfred Timekeeper to Swift. I define one structure, AlfredResult, to keep items to return to a Script Filter in Alfred, a class for using the NSRegularExpression Objective-C class, and the Alfred class for handling everything that an Alfred workflow would need.

At this point, you noticed that I mentioned an Objective-C class. Swift does not remove the need to use Objective-C libraries. The Swift standard library has basic language constructs and routines. Nothing that is operating system specific. All Objective-C libraries are usable directly from Swift. So, don’t throw out all your Objective-C reference manuals. They’re still needed.

The Alfred class has an initialization routine that obtains the different directory paths a workflow would use and create the data and cache directories if they do not already exist. The methods AddResult() and AddResultsSimilar() create the results structure for the XML outputs to Alfred. The AddResultsSimilar() only adds the result if it was similar to the title line. The ToXML() function outputs the XML of the results array.

The Workflow

The example workflow will be a case converter. I created it once in PHP, but for many systems it runs real slow. It will take a string on the Alfred prompt, or from the OSX selection using a hotkey, and give a list of available conversions. It shows the resulting conversion as you type. The conversion the user selects is the one sent to the clipboard and the top application.

Alfred Case Converter Workflow
Alfred Case Converter Workflow

Create an Alfred workflow as you see above.

Workflows Script Filter
Workflow’s Script Filter

Set the ScriptFilter as you see above. Select the Open workflow folder at the bottom right corner. A Finder window will open to the directory for the workflow. Copy the Alfred library file created earlier to this directory. Then create a new file called tcconverter.swift and add this code to the bottom of the file:

This code defines the Converter object. That object creates the different versions of the string and assigns them to the XML results list. Once completely built, it sends the XML to the output.

The Converter object has the TitleCase() method for creating a title case version of the string. It compares each word in the string to the lower case array and the upper case array. If found in these, it sets the word to that value. It always makes sure that the first word is capitalized.

Compiling a library to an application is a little complex. In the Terminal.app or iTerm.app program, run these command lines in the directory that contains the sources.

  1. xcrun swiftc -emit-library -emit-object Alfred.swift -sdk $(xcrun --show-sdk-path --sdk macosx) -module-name Alfred
  2. ar rcs libAlfred.a Alfred.o
  3. xcrun swiftc -emit-module Alfred.swift -sdk $(xcrun --show-sdk-path --sdk macosx) -module-name Alfred
  4. xcrun swiftc -o tcconverter -I "./" -L "./" -lAlfred -sdk $(xcrun --show-sdk-path --sdk macosx) tcconverter.swift

Once all four steps are ran, you will have the tcconverter program in that directory. If you change the tcconverter.swift code, you only have to re-run the last command. If you change the Alfred.swift code, you will have to re-run all four lines.

The program tcconverter should now be in the workflow directory. You can test it in the Alfred prompt:

Testing the Code
Testing the Code

The download file has all of these files and the workflow for you to examine.

Conclusion

In this tutorial I have shown you how to install Swift on the Mac, configure three different program editors and shells, run Swift programs in a terminal, and use Swift to build Alfred workflows

That’s a lot of knowledge that you need to practice to remember. Therefore, go make some great Alfred workflows in Swift and share them with everyone!

Advertisement
Advertisement
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.