Wiki Update: Execute Swift Script

Submitted for your review, comment, and/or revision, the following Wiki article has been updated:

###action: Execute a Swift Script [Keyboard Maestro Wiki]

###Primary Changes

###Confirm or Correct

Swift scripts can get (but not set) Keyboard Maestro Variables by using environment variables

2 Likes

The new code blocks are fine. But the “get (but not set)” is not entirely correct: Not with environment variables, but you can set KM variables from Swift.

The “cheap” way is via a shell process / osascript:

import Foundation

let myString = "This works 👍"
let task = Process()
task.launchPath = "/usr/bin/osascript"
task.arguments = ["-e", "tell application \"Keyboard Maestro Engine\" to setvariable \"fromSwift\" to \"\(myString)\""]
task.launch()

There is another way, but I’m still working on it.


Edit:

OK, here is another way:

import Foundation

let myString = "This works 🙂"
NSAppleScript(source: "tell application \"Keyboard Maestro Engine\" to setvariable \"fromSwift\" to \"\(myString)\"")?
.executeAndReturnError(nil)
1 Like

Just to be clear, this statement is factual, but misleading. Environment Variables can never be used to set KM variables - it doesn’t matter what language or script or whatever.

What Tom is saying is that there are ways to set KM variables from Swift - just not via Environment Variables.

2 Likes

Yes, that’s what I’m saying (or wanted to say). Thanks for the clarification.

1 Like

Dan, since you are a Wiki editor with the knowledge about Swift, could you please update the Wiki to show how to set KM vars via Swift?

Thanks.

Somebody already has updated the article.