Using AppleScript with Swift

For those of you interested in these two languages, I thought you might find this post by the veteran Shane Stanley helpful:

###Swift + AppleScript

Question by Neil Faiman:
Is there a straightforward way to put together an app containing both Swift (or ObjC) and AppleScript code, where the main program is Swift, but it calls into AppleScript to do particular functions?

Response by Shane Stanley:
The other way is to use AppleScriptObjC. You put your scripts in an AppleScript .scpt file in your app's /Contents/Resources, import the AppleScriptObjC framework, and call [[NSBundle mainBundle] loadAppleScriptObjectiveCScripts] early on. Your scripts should be of the form of a script object with a Cocoa class as parent and the handlers in a form compatible with Objective-C conventions:

script SomeClassName
	property parent: class "NSObject"

	on doStuff()
	--
	end doStuff

	on doStuffWith:x
		set x to x as integer
		return x * 2
	end doStuffWith:

end script

You then include the handlers in an @nterface file for the "class", and instantiate your instance:

        self.helperASObject = [[NSClassFromString(@"SomeClassName") alloc] init];

and essentially treat it like a Cocoa class:

NSUInteger val = [self.helperASObject doStuffWith:@4];

The scripting bridge will then convert the common classes (NSString, NSNumbers, NSArray, NSDictionary, etc).

--
Shane Stanley email@hidden
AppleScriptObjC Resources, www.latenightsw.com

1 Like

Thanks – useful link to:

Perhaps the title of this thread is a little confusing ?

(When you say Using AppleScript with Script, I wonder if you mean with Swift ?)

Yes, the title was meant to say “Swift”.