4.6. The repeat with Statement for Lists

The last form of the repeat statement is repeat with. It is used to sequence through the elements in a list. You've only had minimal exposure to lists so far. In Chapter 6, this topic is covered in depth.

If you wanted to set up a simple list that contained the names of four colors, you could write a statement like this:

set myColors to { "aqua", "silver", "brown", "olive" }

As you see in the following Try It Out, the repeat with statement lets you sequence through the elements in a list and assign each one in turn to a variable.

4.6.1.

4.6.1.1. Try It Out: Sequencing through the Elements in a List

You can use repeat with to sequence through list elements.

  1. Type the following program into Script Editor:

    set myColors to { "aqua", "silver", "brown", "olive" }
    
    repeat with theColor in myColors
        log theColor
    end repeat
  2. Click the Event Log tab and run the program. You should see the following in the log:

    (*aqua*)
    (*silver*)
    (*brown*)
    (*olive*)
4.6.1.2. How It Works

The repeat with statement lets you sequence through the elements in a list and assign each one to a variable, in turn. The general format of this statement is

repeat with loopvar in list
    statement
    statement
    ...
end repeat

Execution of the repeat with proceeds as follows: The first element in list, is assigned to the variable loopvar. The body of the loop, the statements that immediately follow up to the end repeat, are then executed. This process is repeated, with each element in ...

Get Beginning AppleScript® now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.