Variables and objects
Use an ordinary assignment when you want to store a value:
shortcut:
greeting = text("Hello")
saved = greeting
variable("🚀: ready [v1]") = greeting
result(greeting)
result(saved)
result(variable("🚀: ready [v1]"))Assignments evaluate once and store a mutable named variable. saved = greeting copies its value; variable("name with spaces") reads or writes an Apple named variable with punctuation or Unicode.
Use name = action(...) if you’ll set the value again. Use output name = action(...) to refer to that particular action’s result without a mutable variable. Names are identifiers, not display labels. Write name, not $name.
An explicit variable("name") operand is the exact name of a mutable native store, not a computed expression or a producer alias. Use JSON escapes when the name contains quotes or a backslash; a doubled backslash before parentheses is part of the name, not an interpolation.
Names are lexical and must exist before use; unknown outputs are source errors. A display-only output_name does not create a source variable. Bind an action result with an ordinary assignment before using it.
To set a result in more than one branch, assign to the same ordinary variable. Two named action outputs don’t merge just because they share a name. Keep imported connections intact. For a new output binding, choose a name other than input, clipboard, item, or repeat_index.
Unpacking native values
Unpack a list or extract several dictionary fields without evaluating the source again:
shortcut:
first, second = unpack([10, 20, 30])
enabled, total = unpack_fields({enabled: false, total: 0}, "enabled", "total")
show(first)
show(second)
show(enabled)
show(total)Use 2–32 distinct variable names on the left. The right side is read once before any variable changes, so left, right = unpack([right, left]) swaps the two values. Reserved names are not allowed.
unpack(source) reads as many items as you named, starting at position 1. Extra items are ignored. Make sure the list has enough items before unpacking it.
unpack_fields(source, "key1", "key2") reads the named fields in that order. Supply one literal, nonempty top-level key per target. Dotted keys, control characters and duplicate keys are rejected. A provably missing literal field is rejected. Extraction does not use truthiness or substitute defaults: existing false and 0 values are read directly.
Nonliteral list inputs retain native item-conversion behavior; static literal checks are not general runtime type validation. Dynamic dictionary-field outputs can remain optional: use an existing presence check such as if let before passing an extracted value to an action that requires a present value.
Check that a list is long enough or that a dictionary has the keys you need before taking values out. Shortcuts can still return nothing or show an error for invalid input. These helpers don’t supply defaults, and you can’t nest them inside another expression or add native annotations.
Properties and dictionary keys
Append a property or dictionary lookup to a reference:
photo.width
file.path
contact.name
payload["title"]
variable("Imported Result")["status"]Use items[index] with a Number index and record[key] with a Text key:
shortcut:
items = ["Tea", "Coffee"]
index = 2
if let drink = items[index]:
show(drink)
record = {title: "Morning"}
key = "title"
if let title = record[key]:
show(title)List indices start at 1. Missing dictionary keys are optional, and brackets do not add bounds checks. A range includes both ends. Use items[2:4] with literals or items[first:last] with Number expressions.
If the index or key type is unknown, use as_type(index, "Number") or as_type(key, "Text") inside the brackets. The equivalent calls are item(items, at: index) and value(record, key: key). Dictionary keys with dots can be interpreted as native key paths.
Objects
object declares a nominal record with fixed typed fields. Constructors require all non-optional fields and reject unknown fields or incompatible values. Objects compile to dictionaries.
shortcut:
object Person:
name: Text
age: Number
nickname: Text?
person = Person(name: "Sam", age: 27)
text(person.name) # Text, known present
if let nickname = person.nickname:
text(nickname)
else:
text("?")Optional fields accept if let or ??; the fallback runs only when the field is absent:
shortcut:
object Person:
name: Text
nickname: Text?
person = Person(name: "Sam")
text(person.nickname ?? "Guest")An optional fallback can leave the result optional; coalescing does not convert an incompatible type.
These deliberately invalid fragments assume the Person declaration above:
Person(name: "A") # error: missing required field: age
Person(name: "A", age: 27, x: 1) # error: Unknown field 'x' for object Person
Person(name: "A", age: "old") # error: Person.age requires Number, got Text
person.bogus # error: Unknown field 'bogus' for object PersonIdentically shaped object declarations remain distinct types; a plain dictionary cannot satisfy an object type. Fields may reference earlier object types, with chained access such as person.home.city. Direct recursive object fields are unsupported; use Dictionary for recursive data.
Declare objects before construction inside shortcut: or a helper body. A helper-local declaration stays in that helper; it does not define an object type for sibling helpers or the caller. Function signatures cannot name body-local objects; use a Dictionary parameter. Reassignment to a non-object loses its nominal type.
Scope and reassignment
shortcut:
total = 0
repeat 3 times:
total = total + 1
result(total)Initialize accumulators before loops. A loop can run zero times; names assigned only in a loop or one branch may be absent afterward. Apply presence checks before required consumers.
Updating dictionary keys in a loop
Compute a Text key and a Text value, then store the dictionary returned by the action. Rebind the same dictionary each time so earlier entries stay in it.
shortcut:
record = {}
for index, label in ["Label 1", "Label 2"]:
round_key = text("Round \(index)")
round_value = text(label)
record = data.set_value(dictionary: record, key: round_key, value: round_value)
show(record)This builds two entries: Round 1 → Label 1 and Round 2 → Label 2. Use supported calls and let Studio encode the variable references.
A lookup uses the same key syntax. Use an if let block when the key might be missing:
shortcut:
record = {"Round 2": "Label 2"}
round_number = 2
if let label = record["Round \(round_number)"]:
show(label)List ranges and dictionary updates
Use a one-based inclusive range to extract part of a list:
shortcut:
middle = slice([10, 20, 30, 40], from: 2, through: 3)
show(middle)This gets items 2 and 3 using Apple Shortcuts’ Get Item from List, set to Items in Range. Count from 1 and include both ends. Use whole numbers up to 2147483647, with the start no greater than the end. If the bounds come from variables, make sure they fit the list; Shortcuts won’t adjust the range for you. The list and its bounds are each read once, in the order written.
Use brackets with computed bounds, just as you would with literals:
shortcut:
values = [10, 20, 30, 40]
first = 2
last = count(values)
tail = values[first:last]
show(tail)values[first:last] and slice(values, from: first, through: last) do the same thing. Provide both endpoints as positive whole numbers, with the start no greater than the end. Neither form clamps ranges or adds runtime bounds checks.
Apply several explicit top-level fields with one expression:
shortcut:
settings = {name: "Old", count: 1}
updated = with_fields(settings, {name: "New", count: 2})
show(updated)with_fields reads the input and the new values once, then returns an updated Dictionary. Assign it back if you want to replace the original variable. It does not promise a deep copy or preserve an object type.
The patch must be a literal dictionary of 1–32 distinct, nonempty keys without dots or control characters. Values may be expressions, but keys must be fixed names. For a key calculated at runtime, write record[key] = value, or use data.set_value if you want the updated dictionary as a result. Existing false/zero values are passed directly without truthiness fallback. Native value conversion still applies; compilation does not prove runtime type preservation on a device. Null and unguarded optional updates are rejected: this is not a deletion helper. Validate dynamic inputs and use presence checks where required.
Both helpers are expression calls and can compose with supported expressions. They do not support direct output bindings. They reject native_id, native_parameters, native_extras and output_name annotations. Neither helper executes or validates actions on an Apple device during compilation. Read exact contracts with get_action("slice") or get_action("with_fields"); use read_reference for language examples.
Selecting list items and dictionary fields
Select non-contiguous list positions in the order you want, including duplicates:
shortcut:
chosen = select_items([10, 20, 30], [3, 1, 3])
show(chosen)The result is [30, 10, 30]. List the positions in the order you want, counting from 1. You can repeat a position. Use 1–32 whole-number positions, each no greater than 2147483647. For a list provided during a run, check that it has enough items. There’s no automatic fallback.
Project a dictionary onto named top-level fields:
shortcut:
profile = select_fields({name: "Sam", enabled: true, count: 3}, ["name", "enabled"])
show(profile)The result is Dictionary, containing only the requested fields, not a preserved nominal object type. The selector is a literal list of 1–32 distinct nonempty Text keys; dots and control characters are unsupported. A known literal missing key is rejected. Unknown runtime missing-key behavior remains native. Do not assume projection validates API responses or supplies defaults.
Both helpers take two positional arguments, read the original once, and keep the selected values rather than turning them into text. They don’t change the original variable or promise a deep copy. Use an ordinary assignment for the result.
Choosing a collection operation
slice(source, from: 2, through: 4): a consecutive, one-based inclusive list range.select_items(source, [4, 1]): selected list positions in a chosen order.unpack(source): bind the first list values to names using documented destructuring syntax.unpack_fields(source, "name", "count"): bind named dictionary fields using documented destructuring syntax.select_fields(source, ["name", "count"]): construct a smaller dictionary.with_fields(source, {count: 2}): produce a dictionary with explicit updates.
Read the matching syntax section before writing a helper call. Inspect optional values before passing them to required consumers. null is not an editable native dictionary field value or a deletion operation: omit the field when appropriate, or use JSON text when an API explicitly requires JSON null. Native action contracts and their coercions remain authoritative.
Compound numeric assignment
shortcut:
total = 10
total += 2
total *= 3
result(total)Use +=, -=, *=, /=, %= or **= on an already assigned mutable numeric variable. total += change means total = total + (change): the left value is captured before the right expression and the right expression is evaluated once. This is numeric arithmetic, not text concatenation, list append or dictionary merge. Unknown, optional or nonnumeric operands need a compatible conversion or presence check first. Field/index targets and undeclared names are unsupported. Formatting preserves compound spelling; native arithmetic limitations still apply.
Saving values between runs
Use storage["key"] = value for a value saved for this shortcut. The type comes from the value you write; a value that might be missing needs a presence check first.
shortcut:
start_page = number(2)
storage["PDFPageRangeStart"] = start_page
if let saved = storage.get("PDFPageRangeStart"):
show(saved + 1)A read can still be missing. If the script hasn’t established its type, use storage.get<Number>("PDFPageRangeStart") to state the expected type. A local dictionary named storage still uses ordinary dictionary assignment.
Missing-value assignment
shortcut:
saved = storage.get<Text>("Greeting")
saved ??= "Hello"
result(saved)name ??= fallback is shorthand for name = name ?? fallback on an already assigned mutable identifier. The fallback runs only when native Has Any Value reports absence. It does not replace present zero or false, and is not a blank-text check. Use is empty for known Text content. Undeclared, constant, field and index targets are unsupported. Native action failures are not caught by a fallback.
Automatic Magic Variable bindings
Write ordinary readable names; do not invent UUIDs or extra preservation syntax:
~~~shortcuty shortcut Photo Note: photo = camera.take_photo(photo_count: 1) recognized = vision.extract_text(image: photo) notes.create(input: recognized) ~~~
This example passes the photo and extracted text straight to the actions that use them, without adding Set Variable steps.
Keep related steps together when you can. Reassigning a value or using it across a branch or loop may require a Set Variable step.
Cross-file variables and shared constants
For global configuration shared with helper files, use shared NAME = literal before Main's shortcut: body. Every reachable imported helper can read the bare name, including in function defaults. Do not import Main from a helper or invent global/export statements. shared belongs only in the entry file; no separate Config file is required. A helper may instead expose its own const through its import namespace.
Shared values are fixed when you write the script. Use literal text, numbers, Booleans, null, lists, or dictionaries, not calls, interpolation, or references to other names. A local parameter, assignment, or constant can use the same name.
Assigning a dictionary field
shortcut:
settings = {"mode": "quiet", "enabled": false}
settings["mode"] = "normal"
show(settings)record["key"] = value means record = with_fields(record, {"key": value}): it updates and rebinds an existing mutable dictionary variable, capturing the source before evaluating the right side once. Use one nonempty literal top-level text key without dots or control characters. This is not a nested path update or numeric list-index assignment. Null values and unguarded optional sources/values are rejected. Nominal object instances cannot use this syntax; construct a new object instead. The returned native dictionary is not a deep-copy guarantee. For a computed key, use record[key] = value:
record = {"name": "Old name"}
key = "name"
record[key] = "New name"The target must already be an assigned mutable dictionary in the current scope. The computed key must be a present Text value, not an unchecked optional or unknown value. The dictionary, key, and right side are evaluated once, left to right; the returned dictionary is assigned back only after the native Set Dictionary Value action. This is equivalent to record = data.set_value(dictionary: record, key: key, value: value), with stricter receiver/key type checks. Empty or dotted computed keys retain that native action’s behavior; this syntax does not validate runtime key contents or promise a deep copy. Typed objects and numeric list-index writes remain unsupported.
Use this form in a shortcut, loop, or helper with its own assigned mutable dictionary; it does not introduce shared state between functions. For a computed read, use record[key] or value(record, key: key). Use if let when the key might be missing. Existing fixed-key writes keep their stricter top-level literal-key rules. Imported calls that expose a separate magic output are not automatically rewritten as rebinding assignments.
Optional native variable declarations
cached: Value? or variable("Cached value"): Value? declares an existing or later-written native named storage slot as Optional<Value>. It only declares the name. It does not store a value, reset anything, or change the previous action’s output. Use it for an existing or later-written named value, not instead of initialization. name = null still performs its normal assignment; an empty list needed before append remains an actual initialization.
Only the literal type Value? is supported for this declaration; it has no initializer. This is a typed binding declaration, not a call, and has no var or native_storage alias.
Declare storage only at the entry shortcut's root, before executable actions. Read an ordinary declared identifier directly; read a quoted/nonidentifier name with variable("Name with spaces"); actual writes remain ordinary assignment or supported named-variable actions. A declaration does not prove a value exists. Guard missing values explicitly; require asserts a type but does not test, alert or halt at runtime.
Duplicate declarations, built-ins, loop aliases and internal names are rejected. The name cannot collide with constants, functions, object names, or same-name immutable output, if-let or magic block-result bindings. Declarations inside functions, branches or loops are rejected. This is not module-shared mutable state or persistent storage across shortcut runs.
shortcut:
variable("Cached value"): Value?
if variable("Cached value") has value:
show(variable("Cached value"))
else:
show("No cached value is available in this run.")The importer uses this declaration for original native named-variable reads with actual Set Variable writers, while retaining the writers' original control-flow scope. It does not convert dangling Magic Variables or list-append initialization into declarations.