AppleScript and Swift — Part 2. Passing parameters.
Learn about AppleScript functions, actual and formal parameters, and NSAppleEventDescriptor — The holy grail.
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.
NSAppleEventDescriptor
is the basic building block for Apple events.
NSAppleEventDescriptor
class is a wrapper for the underlying Apple event descriptor data type,AEDesc
.An instance of
NSAppleEventDescriptor
can represent any kind of descriptor, from a simple value descriptor, to a descriptor list, to a full-fledged Apple event.
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…
NSAppleEventDescriptor(string: "Hello AppleScript")
Passing parameters.
There are 2 ways to write functions in AppleScript: the Objective-C style and the Classic AppleScript style.
Objective-C style:
on doSomething:parameter1
Classic AppleScript style:
on doSomething(parameter1)
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.
let param1 = NSAppleEventDescriptor(string: "Hello AppleScript")
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.
func doSomething(_: NSAppleEventDescriptor) -> NSString
Now, all there’s left to do is (booty) call your function!
let returnVal = doSomething(param1)
Voilà! 🎉