Variables, Constants, & Globals

Table of contents

  1. Variables, Constants, & Globals
    1. Variables
      1. Inline Variables
      2. Get As
      3. Type Coersion
      4. Variable as a Value
    2. Constants
    3. Globals
      1. Ask Each Time
    4. Empty Variables
    5. Add to Variables
      1. Number Value Modifiers
      2. Append Text
      3. Add to Array

Variables

Initialize a variable using the syntax below. Variables work just like they do in Shortcuts. This creates a Set Variable action and assigns the value to a Text action containing “value”.

@identifier = "value"

Variables are not required to be assigned a value:

@identifier

Inline Variables

@text = "value"
@inserted = "Value: {text}"

Get As

@deviceOS = "OS: {Device['OS']}"

@variable = {"Name":"test"}
@getAs = variable['Name']

Type Coersion

@text = "five 5"
@number = "Number: {text.number}"

Variable as a Value

@variable = nil
@ref = variable

Check the value types reference to learn more about variable value types.

Constants

const immutable = 5

Constants are the implementation of Magic Variables as they cannot be modified. When referenced, the output of the action assigned to the constant is used (magic variable) instead of inserting a reference to a variable to which the action output has been saved.

const immutable = 5
alert("{immutable}")

@mutable = 5
alert("{mutable}")

Constants can be used just like variables except that they cannot be redefined or appended to, or the compiler will throw an error.

Array constants are not allowed, as creating an array value involves adding to a variable, and action outputs cannot be added to. Variable reference constants are also not allowed, as the value of a variable can change.

It is recommended to use constants when applicable as it will produce a smaller Shortcut.

Globals

Globals are case-sensitive.

@input = ShortcutInput
@date = CurrentDate
@clipboard = Clipboard
@device = Device

But you can also just inline a global in text like other variables.

@shortcutInput = "{ShortcutInput}"

Ask Each Time

The Ask global may be used for an action argument to prompt the user for input, but may not be used as an inline variable in text.

Empty Variables

You can declare a variable without a value:

@emptyVar
@nilVar = nil

Add to Variables

Add to a variable using the standard += syntax:

Number Value Modifiers

Increment, decrement, multiply, or divide an existing number variable using the following syntax:

@i = 0

/* Add */
@i += 1

/* Subtract */
@i -= 1

/* Multiply */
@i *= 1

/* Divide */
@i /= 1

Append Text

Append text to the end of an existing text variable using the following syntax:

@text = "Existing text"
@text += "Additional text"

Add to Array

Declare an array and use the following syntax to add values to it:

@var = [5, 6]
@var += "test"
@var += 5
@var += {"test": 5}
/* etc... */