Containment Operators

The containment operators test whether the value of one thing is to be found "inside" the value of another. For example, the string "test" contains the string "e". Containment may apply to two strings, two lists, or two records. The result is a boolean.

Containment implies comparison, and the nature of comparisons involving strings can be influenced by a considering clause; see Chapter 19.

It is worth stressing that in the case of list containment, both operands must be lists. In other words, the second operand is not an element; it's a sublist. This is a little counterintuitive at first. To complicate matters, AppleScript fools you by apparently letting you say just what you (wrongly) think you should be allowed to say:

{1, 2} contains 2 -- true

You can say that, but not because it is correct on its face; it's because 2 is coerced to {2} implicitly to get the right syntax, which would be this:

{1, 2} contains {2} -- true

Because the second operand is a sublist, you can ask about more than one element at once:

{1, 2, 3} contains {2, 3} -- true

Lists are ordered, so the items of the sublist you ask about must appear consecutively and in the same order in the target list. These are false:

{1, 2, 3} contains {1, 3} -- false
{1, 2, 3} contains {3, 2} -- false

Because lists can contain lists, you may have to use an explicit extra level to say what you mean:

{{1}, {2}} contains {2} -- false
{{1}, {2}} contains {{2}} -- true

The first is false because 2 is not an element of ...

Get AppleScript: The Definitive Guide, 2nd Edition 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.