Repeat Loop Operation

Repeat loops in a shortcut do not always operate as one might expect, and this arises from the fact that repeat loops create a list from the output of the last action in the loop. This is documented by Apple as follows:

For each iteration of a repeat loop, the last action’s output is gathered into a list, and that list becomes the output of the Repeat action as a whole.

To demonstrate, the following shortcut creates a list that contains 500 instances of the word Hello, and an item in this list is accessed by way of the Repeat Results magic variable. The timing result for this shortcut was 0.92 second.

The following uses the Add to Variable action to create the desired list, but it actually creates two lists. The first is a list that contains 500 items and each item in this list is the word Hello. The second list is the concatenated result of the Add to Variable action, and it contains 125,520 items, each of which is the word Hello. The timing result for this shortcut was 58.2 seconds.

The following is a variation of the above where the repeat loop’s result is the Nothing action. The timing result for this shortcut was 1.07 second.

Anyways, repeat loops are used a lot and it’s good to know how they work.

1 Like

I recently needed to write a Shortcut Quick Action that would allow a user to select individual files or folders and filter just PDFs from the file selection, or the contents of any folder. I used a nested repeat block to add each PDF to a variable. After the repeat blocks, then I passed that list variable to a run AppleScript to process each PDF. The original request was to capture the first two pages of each PDF and write that to the same location with a “_p1-2” suffix.

Click on the image to enlarge.

1 Like