Variables, Constants & Globals

Table of contents

  1. Variables
    1. Variable as a value
  2. Constants
  3. Globals
    1. Ask each time
  4. Empty variables
  5. Add to variables
    1. Numbers
    2. Text
    3. Arrays

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

Insert variables into a text value:

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

Get as…key as a raw string.

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

Type coercion…

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

Variable as a value

@variable = nil
@ref = variable

Get as…

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

Type coercion…

@variable: text
@type = variable.number

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, 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

All globals are implemented. 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:

Numbers

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

Text

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

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

Arrays

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

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