3.4. Nested if Statements

You may recall that the general format of the if statement is as follows:

if Boolean-expression then
    statement
    statement
    ...
end if

The statement that follows the if can be any type of statement at all, even another if statement. You often use additional if statements when you have to make more than just a two-way or simple if-else decision. For example, suppose you are processing some image files, and you want to take different actions depending on the image type. You want to do one thing if the file is a JPEG, another if it's a TIFF, and take a third action if it's a GIF (don't worry if these file types aren't familiar; it's not important).

You find out how to determine a file's type in Chapter 7. For now, assume that the type is stored as a string in a variable called imageType, and you want to test the type and take the appropriate action. You can write a three-way if statement like so:

if imageType = "JPEG" then
    -- perform actions for JPEG file
else
    if imageType = "TIFF" then
        -- perform actions for TIFF file
else
if imageType = "GIF" then
            -- perform actions for GIF file
        end if
    end if
endif

If the image is a JPEG image, some action is presumably performed on the file. Otherwise, a test is made to see if it's a TIFF image. If it is a TIFF, some action is taken on the file. If it's not a JPEG image or a TIFF image, the final test is made to see if it is a GIF image. If it is, an appropriate action is then taken.

Each if statement must be balanced by ...

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.