List Coercions

Anything may be coerced to a list, and will be treated as follows:

  • If the thing you start with is not a collection, the result is a list of one item, and that item is the thing you started with.

  • If the thing you start with is a list, the result is the very same list.

  • If the thing you start with is a record, the result is a list of the values from the record.

Coercion to a list is very useful for making sure you have a list: if the thing you start with isn’t a list, it becomes one, and if it is a list, it is unchanged.

Officially you can’t coerce a list to a record, but there’s a trick for doing it using a second level of evaluation. (Reread the warnings at Section 12.8 before resorting to this trick; remember, it involves a lot of overhead.) Every odd item of the list becomes the name of the record item whose value is the corresponding even item of the list:

on listToRecord(L)
        script myScript
                return {«class usrf»:L}
        end script
        return run script myScript
end listToRecord
listToRecord({"yoho", "haha", "teehee", "giggle"}) 
-- {yoho:"haha", teehee:"giggle"}

A list of one item may be coerced to the datatype of that item, and the result will be that item. Of course, the result can then be coerced to any datatype that it can be coerced to, so you can also coerce a list of one item to that datatype in a single step. For example:

{true} as string -- "true"

That’s possible because the list of one boolean is first coerced to boolean, and a boolean can be coerced to a string.

A list ...

Get AppleScript: The Definitive Guide 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.