Swift scripting instead of AppleScript

At first: happy easter!

I just found out, that Swift also supports scripting. I really like that, because I always struggle with bash (as I always forget everything about bash, because I use it not very often).

But my question is now: Can Swift also be a replacement to AppleScript? For example to create a Service for the Mail.app, so that I can read the content of an e-mail and save the e-mail somewhere?

Interacting with Apple event object model from Swift is a challenge. I’m aware of four options:

  • Legacy C API, <AE/AEDataModel.h> and friends

  • Cocoa scripting Objective-C API, <Foundation/NSAppleEventDescriptor.h> and friends

  • ScriptingBridge

  • Various third-party options

None of these are ideal. Calling the legacy C API from Swift is deeply un-fun. I recently posted an example of this to DevForums.

The Cocoa scripting API is actually pretty reasonable to call from Swift, but it’s a relatively low-level API. Using it for the odd operation here and there is generally OK, but it’s a lot of work to use it for a complex script.

I’m not a big fan of ScriptingBridge. It tries to moosh the Apple event object model into the Objective-C model, and that doesn’t end well. And it’s even weirder when you approach it from Swift.

I’m not able to comment on third-party options.


My preferred approach here is use AppleScript to deal with the Apple event object model stuff — after all, those two were designed in concert — and then invoke the AppleScript from Swift using NSAppleScript. Script’s multiline string literals make it easy to embed your AppleScript in your Swift source.


ps As all this stuff is very Apple-specific, I recommend that you post any follow-up questions to the Xcode > Scripting and Automation topic on DevForums.

Share and Enjoy

Quinn “The Eskimo!” @ DTS @ Apple

5 Likes

Thank you! I just came up testing it. After your post I gave up and tried it with AppleScript itself. If you're used to a language like Swift, it's very hard to stay patient ;) Using Javascript for Automation is a little bit better, but in the end you will fail on using something more complex, for example if you need to create a GUI.

In the end I tried ScriptingBridge and I have to say that it is not that weird as you said. Unfortunately the tools like sdef and sdp will just create Objective-C-Headers, but no Swift files. I started to implement those methods and properties I needed for my application by myself, but it could be worth creating a parser for .sdef-files. Maybe I'll take a closer look to that...