AppleScript and Swift — Part 2. Passing parameters.

Learn about AppleScript functions, actual and formal parameters, and NSAppleEventDescriptor — The holy grail.

Anselm Joseph
Jul 17, 2017 · 2 min read

Okay, so in part 1 I only had to pass variables from Swift to AppleScript, but I didn’t have to edit the variables. Well, I thought that the variables are editable once passed into AppleScript. I thought wrong. 😓

So, here’s what happens when you pass Swift or Objective-C variables (Int, NSInteger, String, NSString, blah blah) to AppleScript.

You can pass Swift or Obj-C variables to AppleScript and access them and output them to the console without breaking a sweat, like in part 1. 👍🏼 The problem arises when you want to edit them. Let’s say you’re passing an Int 2 from Swift to AppleScript. AppleScript understands that you’ve passed an Int, but this Int is a Swift data type and not an AppleScript data type. So, when you try to modify the variable or use it in an equation therein the problem occurs. AppleScript does not implicitly convert this Swift data type to an AppleScript data type.

How do we fix this?

After over 24 hours of trying to understand why my code wasn’t working. With only a very vague missing value error when I tried to add a Swift passed parameter — Int 2 with an AppleScript Integer. I remembered looking at NSAppleEventDescriptor someday. So I started to read on up on it.

If already haven’t figured it out. We use NSAppleEventDescriptor to create values of AppleScript data type, i.e., the AppleScript data type equivalent of Int, String, and so on…

Passing parameters.

There are 2 ways to write functions in AppleScript: the Objective-C style and the Classic AppleScript style.

Read this guide for better understanding.

We’re going to use Objective-C style parameters.

Let’s say you want to pass a String as parameter1.

Create a NSAppleEventDescriptor instance for the string.

Now, in your AppleScript Protocol that you’ve defined use NSAppleEventDescriptor as your data type.

Refer part 1 if you’re confused on how to connect AppleScript and Swift.

Now, all there’s left to do is (booty) call your function!

Voilà! 🎉

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch

Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore

Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store