Can you execute an Applescript script from a Swift Application

I have a simple AppleScript that sends an email. How can I call it from within a Swift application?

(I wasn't able to find the answer via Google.)


As Kamaros suggests, you can call NSApplescript directly without having to launch a separate process via NSTask (as CRGreen suggests.)

Swift Code

let myAppleScript = "..."
var error: NSDictionary?
if let scriptObject = NSAppleScript(source: myAppleScript) {
    if let output: NSAppleEventDescriptor = scriptObject.executeAndReturnError(
                                                                       &error) {
        print(output.stringValue)
    } else if (error != nil) {
        print("error: \(error)")
    }
}

Tested: one can do something like this (arbitrary script path added):

import Foundation
 
let task = Process()
task.launchPath = "/usr/bin/osascript"
task.arguments = ["~/Desktop/testscript.scpt"]
 
task.launch()

For anyone who is getting the warning below for Swift 4, for the line while creating an NSAppleEventDescriptor from zekel's answer

Non-optional expression of type 'NSAppleEventDescriptor' used in a check for optionals

You can get rid of it with this edited short version:

let myAppleScript = "..."
var error: NSDictionary?
if let scriptObject = NSAppleScript(source: myAppleScript) {
    if let outputString = scriptObject.executeAndReturnError(&error).stringValue {
        print(outputString)
    } else if (error != nil) {
        print("error: ", error!)
    }
}

However, you may have also realized; with this method, system logs this message to console everytime you run the script:

AppleEvents: received mach msg which wasn't complex type as expected in getMemoryReference.

Apparently it is a declared bug by an Apple staff developer, and is said to be 'just' a harmless log spam and is scheduled to be removed on future OS updates, as you can see in this very long apple developer forum post and SO question below:

AppleEvents: received mach msg which wasn't complex type as expected in getMemoryReference

Thanks Apple, for those bazillions of junk console logs thrown around.